如果我将点击处理程序绑定到我对跟踪点击感兴趣的元素的祖先,我该如何确定用户是否点击了该元素?
e.g。
function clickHandler(ev) {
// how to determine if a link was clicked from here?
// and also get a reference to that <a> element
// i.e., I want to filter out clicks on <td>s and <span>s, *unless*
// a <span> (or other element) is contained in an <a>, then that still counts!
console.log('click!');
}
&#13;
<table onClick="clickHandler(event)">
<tr>
<td><a href="#">link</a></td>
<td><span>not link</span></td>
</tr>
<tr>
<td>also not a link</td>
<td><a href="#"><span>complex link</span></a></td>
</tr>
</table>
&#13;
答案 0 :(得分:2)
我们可以搜索DOM,直到找到匹配项。
e.g。
function clickHandler(ev) {
var el = closestAncestor(ev.target, 'a', ev.currentTarget);
if (!el) {
console.log('not found');
return;
}
ev.preventDefault();
console.log('found', el.dataset.secret);
}
/**
* Search up through the DOM tree until an element matching the selector is found.
*
* @param {Element} target Element to start searching up from
* @param {string} selector Query selector (passed to {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/matches|matches})
* @param {Element=} context Stop searching if this element is hit
* @returns {Element|null} Found element or null
*/
function closestAncestor(target, selector, context) {
while (target) {
if (target.matches(selector)) {
return target;
}
if (target === context) {
return null;
}
target = target.parentElement;
}
return null;
}
<a href="#" data-secret="should not be found">
<table onClick="clickHandler(event)">
<tr>
<td><a href="#" data-secret="simple link">link</a>
</td>
<td><span>not link</span>
</td>
</tr>
<tr>
<td>also not a link</td>
<td><a href="#" data-secret="complex link"><span>complex link</span></a>
</td>
</tr>
</table>
</a>
答案 1 :(得分:0)
您可以使用活动的目标。在这种情况下。
ev.target
您不仅要将其与当前元素进行比较,还要将其与dom树进行比较,如第二个示例中所示,span可能是目标,但链接是父级,因此您可以假设链接被点击了。您可能还希望通过将类应用于您希望定位的链接来比定位所有链接更具体。
这应该为您提供实际点击的元素。