Let's say i have,
<span class="cls1 cls2" data-bind="title: title" ></span>
I want to add another class via JSON object,
{ 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.
Class binding with Class There are another shorthand way to bind CSS Class to HTML element. className is name of the class, which you want to bind to. condition must return true or false. A return value of true adds the class and a false removes the class.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
KnockoutJS library provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects. It is pure JavaScript Library and works with any web framework. It's not a replacement of JQuery but can work as a supplement providing smart features.
You should use css
binding instead of attr
for this. Read more about it in the documentation: 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/
Using multiple classes:
<span
class="yourClass"
data-bind="css: { myClass: (true == true), theirClass: (!true == false), ourClass: true }"
>Thine Classes</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With