Knockout.js get dom object associated with data

前端 未结 5 2046
别那么骄傲
别那么骄傲 2020-12-23 13:28

I\'m working with knockout.js to build dynamic lists and I\'m trying to figure out how I can get the DOM object associated with an object in my observable array. Specifical

5条回答
  •  滥情空心
    2020-12-23 14:25

    Event handlers like click get passed two arguments. That is

    1. the item that this event belongs to - like the entry of an observable array that you're rendering with the foreach binding ("Item" in your case).

    2. And, an event object, that provides you with more information about the actual event. This object contains the DOM element that got clicked on (key "target"):

      getDomObject = function(item, event) {
          var $this = $(event.target);
          // ...
      }
      

    Just a note: Don't mix knockout and native jQuery DOM manipulations - if you can achieve the same result with clever knockout bindings, I would recommend going with that.

    And here is a simple demo: http://jsfiddle.net/KLK9Z/213/

    var Item = function(color) {
      this.color = String(color);
      this.setTextColor = function(item, event) {
        $(event.target).css('background', color);
      };
    };
    
    ko.applyBindings(new function() {
      this.Items = ko.observableArray([
        new Item('red'),
        new Item('blue'),
        new Item('green')
      ]);
    }());
    li {
      padding: 2px 10px;
    }
    
    
    

提交回复
热议问题