0

Consider the following HTML:

<a href="#" id="aElement" data-bind="click: printId">
   <span id="spanElement">Click Me</span>
</a>

When I click on the link, I have a printId function that is called:

printId: function (item, event) {

    vm.textTest(event.target.id);
}

I would expect that the event.target.id value to be aElement, since that is the element that I have my click binding set to, but instead it is spanElement. Is there a reason why this is the case?

I'm guessing it is because that the actual "substance" that I am clicking on is the span element, but I still think it would make better sense to grab the anchor element instead from a coding standpoint. After all, I may have multiple elements inside that anchor tag and I may want to consistently get a single id every time rather than whatever id might be thrown my way based on where the user clicks inside the anchor tag.

However, this may be a JavaScript issue rather than a knockout issue. Any thoughts?

Here is a fiddle:

JS Fiddle Demo

4

3 回答 3

2

span 中的 click 事件使 DOM 冒泡。使用 event.currentTarget 因为它将引用事件处理程序已附加到的元素。

https://developer.mozilla.org/en-US/docs/Web/API/event.currentTarget

于 2013-08-08T14:19:54.107 回答
2

这是一个 javascript 问题 - 跨度是event.target,因为它是您点击的实际(最里面的)项目。

试试这个 - 在跨度之外添加一些文本,然后单击它 - 你会看到 event.target.id 转到 aElement。

event.currentTarget如果您想要实际放置绑定的项目,请使用。event.currentTarget是监听事件event.target的元素,是接收到事件的元素。

于 2013-08-08T14:20:09.023 回答
1

是的,这与javascript直接相关,而不是淘汰赛。Knockout 只是将实际的 javascript 事件作为参数传递。您可以使用 vanilla javascript 进行检查:

<a href="#" id="aElement" data-bind="click: printId"><span id="spanElement">Click Me</span> test</a>

function test(e) {
 alert(e.target.id + " / " + e.currentTarget.id);
}
document.getElementById('aElement').onclick = test;

如果单击“测试”,则目标 id 将是“a” id。但是如果你点击“Click Me”,你会得到 span id。

见这里:http: //jsfiddle.net/7CCfp/2/

于 2013-08-08T14:24:49.627 回答