简体   繁体   中英

Toggle CSS class KnockoutJS

I have month links

<ul data-bind="foreach: factMonthes">
    <li data-bind="click: $root.changeFactMonth, css:{'selected-month': num == $root.activeFactMonth()}">
</ul>

I want to disable class "selected-month" for all links, except active and enable to active after click. Of course, i can disable class in my method changeFactMonth(), but can i do it with knockout bindings?

function FactMonth(num){
    this.num = num;
    this.name = MonthesNames[num - 1];
    this.active = false;
}

function ViewModel() {

    self.factMonthes = ko.observableArray();       
    self.activeFactMonth = ko.observable(new Date().getMonth() + 1);

    for(var i = 1; i <= 12; i++)
    {
        var month = new FactMonth(i);
        month.active = self.activeFactMonth() == i;
        self.factMonthes.push(month);
    }
}

If month_num is an observable then you need to unwrap it:

<li data-bind="
  click: $root.changeFactMonth, 
  css:{'selected-month': month_num() == $root.activeFactMonth()}
">

You can use observables directly only when you do not use them as part of an expression. Since the comparison ( == ) is an expression, you must use the underlying values, ie you must call the observable.

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