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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top