值更改时不显示淘汰赛 [英] Knockout not displaying when a value changes
问题描述
我尝试使用剔除法来隐藏文本(如果大于某个值).由于某种原因,我无法使其正常工作.当我单击测试"按钮时,应该显示第二个文本字段.
I am trying to use knockout to hide text if greater than a certain value. For some reason I cant get it to work. When I click the test button the second text field should show..
<body class="calc" onLoad="createnav()">
<input type="button" value="test" />
<p data-bind="text: 'This shows', if: 6 > 4" ></p>
<br>
<p data-bind="text: 'This does Not', if: 6 > qty"></p>
这是脚本:
function AppViewModel() {
this.qty = ko.observable("1"); }
// Activates knockout.js
var app = new AppViewModel(); ko.applyBindings(app);
//When I click button I want the name to change
$('input[type=button]').click( function() {
var sum = '5';
app.qty(sum);
});
推荐答案
正如其他人指出的,您正在比较可观察对象qty
而不是其值qty()
As others have pointed out, you're comparing the observable object qty
instead of its value qty()
但是您可能还需要考虑将文本计算为
But you also might want to consider making your text a computed
<p data-bind="text: output"></p>
function AppViewModel() {
var self = this;
this.qty = ko.observable("1");
this.output = ko.computed(function(){
return (6 > self.qty()) ? "This shows too" : "";
});
}
这是一种更像淘汰赛的方式,并且具有将逻辑保留在视图模型中而不是将其混入标记中的优势.
This is a more knockout-like way of doing things, and provides the advantage of keeping your logic inside your view model instead of mixing it in your markup.
在此方法的其他优点中,您将能够在调试时清楚地看到javascript值,并注意到qty是函数而不是数字.
Among other advantages of this, you would have been able to clearly see your javascript values when debugging, and notice that qty was a function rather than a number.
如果要在多个位置显示它,还可以重复使用该值而无需重复计算.
It also allows you to reuse this value without repeating the calculations if you want to show it in multiple places.
这篇关于值更改时不显示淘汰赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!