js - 敲除 无法处理绑定"文本:函数 (){返回



找不到我犯错的地方。 运行代码时收到以下错误消息:

Uncaught ReferenceError: Unable to process binding "text: function (){return quoteAuthor }"
Message: quoteAuthor is not defined

newQuote 可能会向 quotesArray 添加新位置,并导致添加新行 tot able。当 newQuote 没有 ajax 请求时,它工作正常,因此每次都添加了相同的对象。阿贾克斯本人也在工作。不知道该怎么办。 我的网页:

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
<h2>Your quotes</h2>
<table>
<thead>
<tr>
<th>Автор</th>
<th>Цитата</th>
<th>Ссылка</th>
</tr>
</thead>
<tbody data-bind="foreach: quotesArray">
<tr>
<td data-bind="text: quoteAuthor">toDo</td>
<td data-bind="text: quoteText">toDo</td>
<td data-bind="text: quoteLink">toDo</td>
</tr>
</tbody>
</table>
<button data-bind="click: addQuote">Add quote</button>
<script type="text/javascript" src="koQuotesScript.js"></script>
</body>
</html>

我的JS:

function newQuote () {
var self = this;
$.ajax(
{
dataType : "jsonp",
jsonp : "jsonp",
url : "https://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en",
error : function(data) {
alert("Error - 2");
},
success : function(response){
console.log(response);
self.quoteAuthor = response.quoteAuthor;
self.quoteLink = response.quoteLink;
self.quoteText = response.quoteText;
console.log(self);
}
});
}   
function ModelView () {
var self = this;
self.quotesArray = ko.observableArray([
{quoteAuthor: "Neil Alden Armstrong", 
quoteLink: "https://en.wikiquote.org/wiki/Neil_Armstrong", 
quoteText: "That's one small step for man, one giant leap for mankind."},
{quoteAuthor: "Mark Twain (Samuel Langhorne Clemens)", 
quoteLink: "https://en.wikiquote.org/wiki/Mark_Twain", 
quoteText: "If you tell the truth you don't have to remember anything."}
]);
self.addQuote = function () {
self.quotesArray.push(new newQuote());
};
}
ko.applyBindings(new ModelView());

您遇到计时问题,因为您的 ajax 调用是异步的。首次调用newQuote()时,会立即将新对象添加到数组中,但该对象缺少 quoteAuthor 属性。它根本不缺少任何属性,直到您的 ajax 调用返回,此时这些属性被定义,但与此同时 KNOCKOUT 不知道要绑定到什么。

您可以为这三个属性提供报价对象的默认值,也可以重构代码,以便在 ajax 调用返回之前不会将对象添加到数组中。

最新更新