简体   繁体   English

如果单击其中的链接,请勿触发div click事件

[英]Do not trigger div click event if a link inside of it is clicked

I have a div that expands when clicked. 单击时,我的div会扩展。 I also have a link inside this div. 我在这个div内也有一个链接。 Expected behavior is for the click event to be ignored when the link is clicked, but obviously clicking anywhere in the div will trigger the event. 预期的行为是单击链接时会忽略click事件,但是显然单击div中的任何位置都会触发该事件。 I've tried stopPropagation(), but it doesn't seem to work. 我已经尝试过stopPropagation(),但是它似乎不起作用。

$('#infobox').on('click', expandFunction);

$('#infobox a').on('click', function(event) {
  event.stopImmediatePropagation();
});

<div class="infobox">
  <a href="#">Link</a>
</div>

 function expandFunction() { alert("expanded") } document.getElementById("infobox").addEventListener('click', function (event) { if (event.target.tagName != event.currentTarget.tagName) return; expandFunction(); }); document.querySelector("#infobox a").addEventListener('click', function (event) { alert("linkclicked") }) 
 div{ padding:15px; background-color:gray; } a{ padding:15px; background-color:silver; color:white; margin:5px; display:inline-block } 
 <div id="infobox" class="infobox"> <a href="#">Link</a> </div> 

first you must set Id for infobox 首先,您必须为信息框设置ID

<div id="infobox" class="infobox">

you can use this code to prevent click from other elements 您可以使用此代码来防止其他元素的点击

$('#infobox').on('click', function(event){ 
if(event.target.id!= event.currentTarget.id) return;
expandFunction();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM