Knockout JS - CSS Binding with dash in class name

自闭症网瘾萝莉.ら 提交于 2019-12-22 01:13:28

问题


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



来源:https://stackoverflow.com/questions/10283328/knockout-js-css-binding-with-dash-in-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!