Knockout 将 css 类绑定到观察到的模型属性
我想将 divs css 类绑定到视图模型的属性,如下所示:
<div id="statusIndicator" data-bind="css: selectedPriority">
但这会生成结果:
<div id="statusIndicator" class=" 0 1 2 3">
这是视图模型:
myViewModel = {
selectedPriority: ko.observable('High'),
Company: ko.observable("Bert"),
Rows: ko.observableArray([
new row(),
new row(),
new row()
]),
Tabs: ['High', 'Medium', 'Low'],
selectPriority: function (tab) {
this.selectedPriority(tab);
}
};
因此,当我加载使用此视图模型的页面时,我希望 div 是:
<div id="statusIndicator" class="High">
什么是我做错了吗?
I want to bind a divs css class to a property of the view model like this:
<div id="statusIndicator" data-bind="css: selectedPriority">
But this generates the result:
<div id="statusIndicator" class=" 0 1 2 3">
This is the view model:
myViewModel = {
selectedPriority: ko.observable('High'),
Company: ko.observable("Bert"),
Rows: ko.observableArray([
new row(),
new row(),
new row()
]),
Tabs: ['High', 'Medium', 'Low'],
selectPriority: function (tab) {
this.selectedPriority(tab);
}
};
So when i load the page that uses this view model i want the div to be:
<div id="statusIndicator" class="High">
What am i doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于这种情况,您可以这样做:
此方法的唯一缺点是它将直接设置类,而不是打开或关闭类,因此如果您使用多个类,则
selectedPriority
将需要包含完整的类列表。For this situation you can do:
The only downside to this method is that it will set the class directly rather than toggle a class on or off, so if you are using multiple classes, then
selectedPriority
would need to contain the complete list of classes.看起来您无法直接从模型设置类:http://knockoutjs.com/documentation/css-binding。 html
你不能做这样的事情:
Looks like you can't set a class directly from your model: http://knockoutjs.com/documentation/css-binding.html
You can't do something like this:
正如@Chris Jaynes 在评论中所暗示的,Knockout 2.2 .0 使设置类名变得容易,Knockout 作者 Steve Sanderson 在博客文章中详细介绍了这一点。
http://blog.stevensanderson.com/2012/ 10/29/knockout-2-2-0-released/
根据帖子:
该博客文章还包含一个 jsfiddle,您可以使用它来查看操作中的绑定。
http://jsfiddle.net/qRmfH/light/
注意
css
在他的示例中,绑定语法是css: selectedTicketCss
,它是一个 计算的 observable 返回 css 类名:As hinted at in comments by @Chris Jaynes, Knockout 2.2.0 makes setting class names easy, as detailed in a blog post by Knockout author Steve Sanderson.
http://blog.stevensanderson.com/2012/10/29/knockout-2-2-0-released/
As per the post:
The blog post also includes a jsfiddle you can play with to see the binding in action.
http://jsfiddle.net/qRmfH/light/
Note the
css
binding syntax in his example,css: chosenTicketCss
, which is a computed observable that returns a css class name: