我怎样才能获得目标点击元素,即使这个元素在其他元素中具有相同类型,如(div)
我在彼此内部有3个div,当我宣布div的点击事件时,我点击了顶部div我也为父母点了3个点击事件。
所以我只想点击一下我点击的目标元素点击事件并忽略其他
我的尝试
jQuery('div').click(function(e) {
var clicked = jQuery(e.target);
// Ensure we're checking which list item is clicked,
// other children should be allowed
if(clicked.parents().length > 0) {
// :first ensures we do not select higher level list items
alert($(clicked).html());
return ;
}
else
{
alert($(clicked).html());
}
});
答案 0 :(得分:3)
您可以尝试在Click事件处理程序中添加e.stopPropagation()
。这将允许事件在点击的任何div上触发,但是阻止事件进一步向上移动。
答案 1 :(得分:1)
执行stopPropagation
是一种方法。我认为,更好的方法是检查当前元素是否与事件目标相同,这意味着您仍然可以处理树上更高处理程序的事件:
jQuery('div').click(function(e) {
if (this === e.target) {
// we're handling on the clicked element
}
}
答案 2 :(得分:0)
您需要停止向DOM树传播的点击事件。