JavaScript
function productBox(event){
event.stopPropagation();
console.log(event.target);
}
var product = document.getElementsByClassName('product');
for (var g = 0, length = product.length; g < length; g++){
console.log('here');
product[g].addEventListener('click',productBox);
}
HTML
<div class="product">
<div class="productContent">
<img src="file:///C|/Users/Jacob/Downloads/12939681_1597112303636437_733183642_n.png" />
</div>
<div class="productName">
Here
</div>
<div class="productDescription">
</div>
所以问题就出在product元素被点击时,event.target返回事件监听器的实际子元素。例如,我单击一个“产品”,它会返回 productContent、productName 或 productDescription 作为目标,而实际上我想要的是“产品”元素,然后执行 .childNodes 并在其中找到图像。
请注意 jQuery 不是一个选项,它有 30kb 的东西我不会使用,因为这是一个几乎没有任何 javascript 的静态 html 页面。
我想也许,
检查元素是否为“产品”,如果不是,则获取父级并检查它是否是“产品”,如果不是则转到该父级,依此类推。然后在其中找到 img 标签。但我觉得这是一项冗长的工作。
有什么想法吗?
最佳答案
要获取处理程序绑定(bind)到的元素,您可以在处理程序中使用 this
。
作为@DaveNewton指出,event
对象有一个 .currentTarget
也可以使用的属性。这很好,因为您可以使用 .bind()
拥有手动绑定(bind) this
的函数,或者您可能正在使用 new arrow functions ,它有一个由其原始环境定义的 this
,因此不可能以这种方式获取绑定(bind)元素。
关于javascript - 当 event.target 返回子元素时,如何只获取点击事件的父元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36664786/