简体   繁体   English

防止点击事件触发父操作

[英]Prevent click event triggering parent action

I have lis containing anchor tags for deleting that particular li. 我有lis包含用于删除该特定li的锚标记。 So, I have onclick event for both anchor tag and li. 因此,锚标签和li都有onclick事件。 Clicking on li opens up a modal window and click on anchor tag is supposed to hide that li. 单击li将打开一个模态窗口,然后单击锚标记以隐藏该li。

How can I trigger click event on anchor tag without it triggering li click event. 如何在锚标记上触发click事件,而不触发li click事件。 Here is what I have tired so far: 到目前为止,这是我很累的事情:

JS: JS:

$('body').on('click', 'a', function(e) {
    if(confirm('Are you sure you want to delete it?') == true){
        $(this).parent().hide();
    }
    //e.preventDefault();     
    e.stopPropagation();   
});

HTML: HTML:

<li onclick="openModal(0)">
  <a class="closer">X</a>
  <h3>Lolita</h3>
  <p>Check it</p>
</li>

Here's a fiddle with your answer: https://jsfiddle.net/jimedelstein/bsg4jq3m/ 这是您的答案的小提琴: https : //jsfiddle.net/jimedelstein/bsg4jq3m/

You need to detect the target of the click, and if it's the link ignore it, otherwise trigger the li click. 您需要检测点击的目标,如果是链接,则忽略它,否则触发点击。

<li>
  <a class="closer">X</a>
  <h3>Lolita</h3>
  <p>Check it</p>
</li>


$('body').on('click', 'a', function(e) {
    if(confirm('Are you sure you want to delete it?') == true){
        $(this).parent().hide();
    } 
    e.stopPropagation();   
});

function openModal(e){
    if (e.target != $("a.closer")[0]){
     alert("not the link!");
  }
};

$("li").on("click", openModal);

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

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