knockoutjs get element id through click event

北慕城南 提交于 2019-12-03 09:46:15

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.

Dirk Boer

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;

Html Binding

 <input type="checkbox" data-bind="attr:{id: $data.Id , Qref: '3177'} , click: $root.answerClick">&nbsp;&nbsp;&nbsp;<span data-bind="text: $data.Text , attr:{id: $data.Id}"></span>

js code

answerClick: function(c, event){
        var element = event.target;
        var qref = element.getAttribute('Qref');
        var click_id = element.id;
        return true;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!