Add striped styling to a list of items

前端 未结 6 984
执笔经年
执笔经年 2021-02-01 17:43

What would be the best way to stripe a list with KnockoutJS? The class on the div below should be even or odd depending where it is in the list, and update when adding or removi

6条回答
  •  逝去的感伤
    2021-02-01 18:09

    There was a topic for this on the KO forums a while back here: https://groups.google.com/d/topic/knockoutjs/cJ2_2QaIJdA/discussion

    The solution that I had was a custom binding. There were a couple variations on it, but it basically would look like:

    ko.bindingHandlers.stripe = {
        update: function(element, valueAccessor, allBindingsAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor()); //creates the dependency
            var allBindings = allBindingsAccessor();
            var even = allBindings.evenClass;
            var odd = allBindings.oddClass;
    
            //update odd rows
            $(element).children(":nth-child(odd)").addClass(odd).removeClass(even);
            //update even rows
            $(element).children(":nth-child(even)").addClass(even).removeClass(odd);;
        }
    }
    

    and be used like:

      Sample here with 3 variations of this binding:

      http://jsfiddle.net/rniemeyer/HJ8zJ/

    提交回复
    热议问题