简体   繁体   中英

How can I add a class using Knockout JS?

I'm trying out Knockout for the first time and have gone through the basic tutorial and looked at various examples.

But trying it myself (jsFiddle) does not quite work.

All I want to do, is to add the class open to a div when clicking a "Click me" text.

What am I missing here?

//HTML
<div class="clickMe" data-bind="click: expand">Click me</div>

<div class="wrapper">        
    <div class="content" data-bind="css: {expandMenu : open}">
      This is a test
    </div>
</div>

//JS
function viewModel() {
    var self = this;

    self.expandMenu = ko.observable(false);

    self.expand = function () {
        self.expandMenu(!self.expandMenu());
    };
};
ko.applyBindings(new viewModel());

// CSS
.content {display: none;}
.content.open {display: block;}    

To fix this switch class name with observable in css binding:

data-bind="css: {open : expandMenu}"

Also, you can use css binding is such formats:

data-bind="css: getClassForSomething()" // getClassForSomething must return css class (string)

and

data-bind="css: { open: isSomethingDone() }" // considering that isSomethingDone is viewmodel's method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM