jQuery Knockoutjs 通过点击事件获取元素 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11158045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:15:45  来源:igfitidea点击:

knockoutjs get element id through click event

jqueryknockout.jsknockout-2.0

提问by bdev

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

我正在使用knockoutjs,目前我认为有如下内容:

<img id="myTab1" data-bind="click: pressedTab.bind($data, '#myTab1')" src="images/image1.png"></img>

This allows me to get the element ID in my view model:

这允许我在我的视图模型中获取元素 ID:

pressedTab = function(tab){
    console.log("Element ID: " + tab);
}

This writes:

这写道:

Element ID: #myTab1

元素 ID:#myTab1

However, it's too repetitive to send the name of the img id in the click event. Is there a way to send the img id without explicitly re-writing it?

但是,在click事件中发送img id的名称太重复了。有没有办法在不明确重写的情况下发送 img id?

回答by madcapnmckay

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

您实际上可以通过 KO 单击处理程序访问事件对象。

<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/

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

Hope this helps.

希望这可以帮助。

回答by 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.

madcapnmckay 的答案并不完全正确。您可以更好地使用 currentTarget:当您有一个带有嵌套元素的 div 时,它将返回原始绑定元素而不是子元素。

See this question

看到这个问题

Update

更新

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

正如@Ryan 提到的 - event.currentTarget 不适用于 IE8。对于 <= IE8 支持,您可以使用:

var target = (event.currentTarget) ? event.currentTarget : event.srcElement;

回答by San Jaisy

Html Binding

Html 绑定

 <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

js代码

answerClick: function(c, event){
        var element = event.target;
        var qref = element.getAttribute('Qref');
        var click_id = element.id;
        return true;
    }