在两个不同的DIV中定义两个FOREACH,如下所示
<div style="background-color:black; color:white; overflow:scroll; height:350px;width:300px">
<ol data-bind="foreach: price_quantity">
<li data-bind="text: quantity + ' &&& ' + price"></li>
</ol>
</div>
<div style="background-color:black; color:white; overflow:scroll; height:350px;width:300px">
<ul data-bind="foreach: papers" style="list-style-type:none">
<li>
<div data-bind="text: paperName"></div>
<ul data-bind="foreach : _colors" >
<li>
<div data-bind="style:{'background-color' : colorName}" style="height:25px;width:25px;border:1px solid white"></div>
</li>
</ul>
</li>
</ul>
</div>
在 $(document).ready 上,我正在进行两个 AJAX 调用,如下所示,以使用 LIST 填充上面的两个div
<script type="text/javascript">
$(document).ready(function () {
var sku = "abcd";
$.ajax({
url: "/api/values?clientSKU=" + sku,
dataType: "json",
asyc: true,
type: "get",
success: function (msg) {
var skuandprice = $.parseJSON(msg);
ko.applyBindings(new ViewPriceObjectOnWeb(skuandprice));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
}
});
var appid= "123";
$.ajax({
url: "/api/Default1?app_id=" + appid,
dataType: "json",
asyc: false,
type: "get",
success: function (msg) {
var paperandcolors = $.parseJSON(msg);
ko.applyBindings(new PaperModal(paperandcolors));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
}
});
});
function ViewPriceObjectOnWeb(d) {
this.price_quantity = ko.observableArray(d);
}
function PaperModal(paperArr) {
this.papers = ko.observableArray(paperArr);
}
如果我通过评论一个或另一个 DIV 来运行它们并且不进行相应的调用,它工作正常。
当页面加载时同时包含 DIVS 及其列表,它给出的错误
无法分析绑定。 消息:引用错误:"price_quantity"未定义; 绑定值:foreach:price_quantity
为什么这行不通?任何帮助都非常感谢。
当您多次应用绑定时,您需要指定它将引用哪个 DOM 元素。在您的情况下,您需要执行以下操作:
ko.applyBindings(new ViewPriceObjectOnWeb(skuandprice), document.getElementById("divQuantity"));
HTML是:
<div id="divQuantity" style="background-color:black; color:white; overflow:scroll; height:350px;width:300px">
<ol data-bind="foreach: price_quantity">
与第二个绑定相同。
但实际上我建议将绑定与更新模型分开。这意味着您将在加载任何数据之前在某处单独调用此绑定代码。加载数据时,只需更新模型:
var ViewPriceObjectOnWeb = function()
{
var self = this;
self.price_quantity = ko.observableArray(0);
};
...
var priceObject = new ViewPriceObjectOnWeb();
ko.applyBindings(priceObject, document.getElementById("divQuantity"));
...
$.ajax({
url: "/api/values?clientSKU=" + sku,
dataType: "json",
asyc: true,
type: "get",
success: function (msg) {
priceObject.price_quantity = $.parseJSON(msg);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
}
});
knockoutjs 非常聪明,所以它会在模型更新后立即更新 DOM 元素。