Knockout JS - CSS Binding with dash in class name

2019-04-17 18:37发布

问题:

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?

回答1:

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>


回答2:

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