如何在knockout.js 中进行条件绑定? [英] How can I make conditional binding in knockout.js?
本文介绍了如何在knockout.js 中进行条件绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过这个:
<div data-bind="attr: {class: itemSelected? 'selected' : 'unselected' }"></div>
但它不起作用:)
推荐答案
假设你有这个:
function viewModel() {
this.itemSelected = ko.observable(true);
}
ko.applyBindings(new viewModel());
在 itemSelected 后加一个 () 来获取可以与三元运算符一起使用的 observable 的当前值:
Add a () after itemSelected to get the current value of the observable that you can use with the ternary operator:
<div data-bind="attr: { class: itemSelected() ? 'selected' : 'unselected' }"></div>
如果您不需要为非选择状态分配未选择的类,您可以改为这样做:
If you didn't need to assign the unselected class for the non selected state you could do this instead:
<div data-bind="css: { selected: itemSelected }"></div>
这篇关于如何在knockout.js 中进行条件绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文