javascript - 防止点击事件触发父操作

标签 javascript jquery html

我有包含用于删除该特定 li 的 anchor 标记的 li。 所以,我有 anchor 标记和 li 的 onclick 事件。单击 li 打开一个模式窗口,单击 anchor 标记应该隐藏该 li。

如何在 anchor 标记上触发单击事件而不触发 li 单击事件。 这是到目前为止我已经厌倦的:

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>

最佳答案

这是你的答案:https://jsfiddle.net/jimedelstein/bsg4jq3m/

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

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

关于javascript - 防止点击事件触发父操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35553898/

相关文章:

javascript - 如果多次运行工厂,JavaScript 工厂中的数据将被覆盖

javascript - slider - 在 HTML 视频中添加标题

javascript - 单击后启动自动完成

javascript - Angular : updating view with value passed from directive to controller

javascript - 等待图像加载到 angularjs 工厂内

javascript - 如何将多个数组中的项目添加到另一个数组中?

javascript - 选择单选按钮时启用单击按钮

javascript - 将事件添加到 HTML 输入数组的所有元素并获取数组中的值

javascript - 在显示/隐藏 div 图像后,图像出现在原始图像旁边而不是替换它

css - 将 sub-div 的宽度扩展到 100%