knockoutjs get element id through click event

前端 未结 2 1175
闹比i
闹比i 2021-02-12 10:50

I\'m using knockoutjs and I currently have something in my view that looks like this:



        
相关标签:
2条回答
  • 2021-02-12 11:15

    The answer of madcapnmckay is not completely correct. You can better use currentTarget: it will return the original bound element instead of a child element, when i.e. you have a div with nested elements in it.

    See this question

    Update

    As @Ryan mentioned - event.currentTarget is not available for IE8. For <= IE8 support you can use:

    var target = (event.currentTarget) ? event.currentTarget : event.srcElement;
    
    0 讨论(0)
  • 2021-02-12 11:21

    You actually can get access to the event object via a KO click handler.

    <button id="somebutton" data-bind="click: log">Click Me </button>
    
    var ViewModel = function() {
        this.log = function(data, event) {
            console.log("you clicked " + event.target.id);
        }
    };
    ko.applyBindings(new ViewModel());
    

    http://jsfiddle.net/madcapnmckay/e8JPT/

    Hope this helps.

    0 讨论(0)
提交回复
热议问题