[英]How do you handle anchor inside a div with a click event bound to it without triggering the div click event
I have a div with a click event bound to it. 我有一个绑定了click事件的div。 I want to add an anchor tag inside this div that will not trigger the action of the div click. 我想在此div中添加一个锚标记,该标记不会触发div点击的操作。 I have tried putting 'onclick="return false;"'
on the anchor but it still triggers the click on the div. 我曾尝试在锚点上放置'onclick="return false;"'
,但它仍会触发对div的点击。 Is there a trick to this? 有这个窍门吗?
Given that you're using jQuery's click()
, you can do: 假设您正在使用jQuery的click()
,则可以执行以下操作:
$('div').click(
function(e){
if (e.target.tagName == 'A') {
return false; // do nothing if the click is on the a element
}
else {
// do something else
}
});
Or: 要么:
$('a').click(
function(e){
e.stopPropagation(); // stops the click moving up to the parent elements
});
To prevent it you should prevent event bubbling. 为了防止它,您应该防止事件冒泡。 For no w3c browsers there is cancelBubble property other ways there is stopPropagation. 对于没有w3c浏览器的人,有cancelBubble属性,而其他方法有stopPropagation。
In the way you want to use it better to set events in one style. 以这种方式,您想更好地使用它来以一种样式设置事件。 For the case jquery has: event.stopPropagation and event.stopImmediatePropagation methods to prevent it bubbling with one way in all browsers. 对于这种情况,jquery具有: event.stopPropagation和event.stopImmediatePropagation方法,以防止jquery在所有浏览器中冒泡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.