Knockout JS - CSS Binding with dash in class name

2019-04-17 18:40发布

I have a data binding in Knockout to apply a CSS class if a condition is true. When I use a dash in the class name (such as test-class) then I get a javascript error.

Here is a fiddle that demonstrates the problem: http://jsfiddle.net/sgvem/2/

<p data-bind="text: property, css: { with-dash: property().length > 0 }"></p>

Is there a way to add a class with a dash using Knockout JS?

2条回答
霸刀☆藐视天下
2楼-- · 2019-04-17 19:24

You can qualify the name using '

Like this:

<p data-bind="text: property, css: { 'with-dash': property().length > 0 }"></p>

Your Fiddle, updated

Here are the Knockout docs explaining the css binding: http://knockoutjs.com/documentation/css-binding.html

查看更多
叛逆
3楼-- · 2019-04-17 19:40

Just put it in quotes:

<p data-bind="text: property, css: { 'with-dash': property().length > 0 }"></p>

Here's an updated fiddle.

As a side note, you don't need the > 0 since a length of 0 will evaluate to false, and any other length will evaluate to true:

<p data-bind="text: property, css: { 'with-dash': property().length }"></p>
查看更多
登录 后发表回答