【问题标题】:How to Deativate parent element click event if child anchor tag is clicked? [duplicate]如果单击子锚标记,如何停用父元素单击事件? [复制]
【发布时间】:2016-09-18 04:40:38
【问题描述】:

我有一种情况,我正在从我的数据库中创建动态内容。我正在其中创建<div>,其中包含内容。我添加了onclick 事件<div>。如果用户单击 div 的内容,这意味着在 <div> 上,它会打开一个弹出窗口。但是如果内容中有锚标签。那时如果用户点击锚标签,事件都会执行它也会打开链接页面并弹出。

我想在单击锚标记时阻止该 div onclick。

有什么可以帮助我的吗?

【问题讨论】:

  • 因为您在服务器端生成内容,或者至少听起来是这样。您最好的选择可能是将 onclick 处理程序添加为属性。 onclick="return false;"

标签: javascript jquery html css


【解决方案1】:

如果你使用 jQuery,试试这样的 stopPropagation() 函数:

简单示例:

$("div a").click(function(e) {
    e.stopPropagation();
    // your code here...
});

或带有类和 ID 的增强示例:

html:

<div id="content">
    ...
    <a href="/your/uri/here" class="noPropagation">my link</a>
    ...
</div>

js:

$("div#content a.noPropagation").click(function(e) {
    e.stopPropagation();
    // your code here...
});

这里是文档:https://api.jquery.com/event.stoppropagation/

【讨论】:

    【解决方案2】:

    这是一个例子https://jsfiddle.net/7c51j7av/

    <div class="outer">
        <div class="inner">
        click me
        </div>
     </div>  
    
    
    
    $(".outer").click(function(){
            alert("Here");
        });
    
        $(".inner").click(function(e){
            e.stopPropagation();
            alert("Stopped it");
        });
    

    【讨论】:

      【解决方案3】:

      由于您要动态添加&lt;div&gt;,因此您可以将点击事件处理程序绑定到与动态内容最近的祖先。这是一种方法:

      $('.some-container').on('click', 'div.dynamic-content a', function(event) {
          event.stopPropagation();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-02
        相关资源
        最近更新 更多