我正在尝试使用KnockoutJS进行两个动态操作。
首先,如果值是true,我想应用特定的css规则,而且我想再次切换表行的可见性,以检查相同的值,如果它是true,则显示div。
这是我拥有的:
<th class="name" data-bind="css: { text_linethrough: !$root.HasDiscount() }, text: '$' + (Price)"></th>
<tr data-bind="visible: $root.HasDiscount(), css: { package5_Discount_Background: Name == 'Cady Kids Package 5' }">
<th class="name" style="width: 60% !important;"><span></span>
</th>
<th class="name">
PRE-ORDER PRICE:
</th>
<th class="name" data-bind="text: '$' + (Price - 10)"></th>
</tr>
因此,如果$ root.HasDiscount()返回true,那么我希望这两个CSS都将被应用,并且表行将可见。
尽管该值为true,但我仍然没有获得正确的CSS规则,并且该行仍然不可见。
这是HasDiscount值的创建方式:
t.HasDiscount = ko.computed(function() {
$.ajax({
type: "POST",
url: "/webservices/Shopping.asmx/checkShowDiscountedPrice",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (i) {
if (i.d) {
return i.d;
} else {
return false;
}
},
error: function (n) {
u(n);
}
});
return false;
});
您不应该像这样在计算机内部进行ajax调用。这是一个异步调用,这意味着该函数在对服务器的调用进行往返之前返回,导致最终触发的return false始终触发。
您可以尝试
t.HasDiscount = ko.computed(function() {
$.ajax({
type: "POST",
url: "/webservices/Shopping.asmx/checkShowDiscountedPrice",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (i) {
if (i.d) {
return i.d;
} else {
return false;
}
},
error: function (n) {
u(n);
}
});
return false;
});
但我怀疑这是最佳做法
我将分别进行ajax调用,并在返回时更新可观察的值。然后在计算所得的值中返回该可观察的属性。
function someOtherFunction(){
$.ajax({
type: "POST",
url: "/webservices/Shopping.asmx/checkShowDiscountedPrice",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (i) {
if (i.d) {
t.HasDiscount (i.d);
} else {
t.HasDiscount (false);
}
},
error: function (n) {
u(n);
}
});
}
t.HasDiscount = ko.observable(false);