阻止单击事件触发父操作

时间:2016-02-22 12:36:53

标签: javascript jquery html

我有lis包含用于删除特定li的锚标签。 所以,我有锚标记和li的onclick事件。点击li打开一个模态窗口,点击锚标签应该隐藏那个li。

如何在不触发li click事件的情况下触发锚标记上的click事件。 这是我到目前为止所厌倦的:

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:

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

1 个答案:

答案 0 :(得分:1)

这里有一个小提琴你的答案:here

您需要检测点击的目标,如果链接忽略它,否则触发点击。

<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);