Javascript 如何在knockoutjs中添加动态类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14255339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a dynamic class in knockoutjs?
提问by user960567
Let's say i have,
假设我有,
<span class="cls1 cls2" data-bind="title: title" ></span>
I want to add another class via JSON object,
我想通过 JSON 对象添加另一个类,
{ title: 'a', clas: 'cls3' }
This work's,
这部作品,
<span class="cls1 cls2" data-bind="attr:{title: title,'class': 'cls1 cls2'+clas}" ></span>
But the problem is that it will add two class attributes. I need the cls1 and cls2 class on beginning. But need cls3 class after some event.
但问题是它会添加两个类属性。我在开始时需要 cls1 和 cls2 类。但是在某些事件之后需要 cls3 类。
回答by Artem Vyshniakov
You should use cssbinding instead of attrfor this. Read more about it in the documentation: http://knockoutjs.com/documentation/css-binding.html.
您应该使用css绑定而不是attr为此。在文档中阅读更多相关信息:http: //knockoutjs.com/documentation/css-binding.html。
You code will look something like this:
您的代码将如下所示:
<span class="cls1 cls2" data-bind="text: title, css: myClass" ></span>
Here is working fiddle: http://jsfiddle.net/vyshniakov/gKaRF/
这是工作小提琴:http: //jsfiddle.net/vyshniakov/gKaRF/
回答by Cody
Using multiple classes:
使用多个类:
<span
class="yourClass"
data-bind="css: { myClass: (true == true), theirClass: (!true == false), ourClass: true }"
>Thine Classes</span>
回答by vfportero
You can use the cssbinding to do this:
您可以使用css绑定来执行此操作:
<span class="cls1 cls3" data-bind="css: clas"/>
This adds the value of your "clas" property to the current class collection of the element
这会将“class”属性的值添加到元素的当前类集合中

