【问题标题】:Prevent click event triggering parent action防止点击事件触发父动作
【发布时间】:2016-06-03 21:28:08
【问题描述】:

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

如何在锚标记上触发点击事件而不触发 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>

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

这是你的答案: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);

【讨论】:

    猜你喜欢
    • 2015-04-28
    • 1970-01-01
    • 2022-07-13
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多