【问题标题】:Stop parent event jquery [duplicate]停止父事件jquery [重复]
【发布时间】:2012-05-09 12:52:44
【问题描述】:

我想在单击子链接时停止父事件触发。这是我的代码:

$('.list_row_inputtype').on('click',function(event) {

    $(this).find('a.link_to_fire').click();
    event.stopPropagation();
  
    return false;
});


<div class="list_row_input_type unread"> 
    <a href="#" onclick="toogleRead(); return false;" class="toogleRead"></a>
    <a href="{corePath}/mails" class="link_to_fire">{emailLink}</a>
    <div class="description"></div>
</div>

当我点击.toogleRead 时,它会触发该功能,但也会切换到{corePath}/mails 页面。我想阻止它改变页面。

【问题讨论】:

    标签: jquery jquery-events stoppropagation


    【解决方案1】:

    您也应该通过 jQuery 在.toogleRead 元素上添加事件处理程序。更容易记住处理程序的附加位置,它不会混合两种方式,并且在 HTML 和 Javascript 之间添加了更好的分离。

    这是一个工作演示 http://jsfiddle.net/pomeh/uFV9R/

    HTML 代码

    <div class="list_row_input_type unread"> 
        <a href="#" class="toogleRead"></a>
        <a href="{corePath}/mails" class="link_to_fire">{emailLink}</a>
        <div class="description"></div>
    </div>
    

    Javascript 代码

    $('.list_row_input_type').on('click',function(event) {
        event.stopPropagation();
        // your stuff
    });
    
    $('a.toogleRead').on('click',function(event) {
        event.stopPropagation();
    });
    

    另外一点,在大多数情况下,使用 jQuery 从事件处理程序返回 false 是一种不好的做法。它做了太多你通常只想做其中一件的事情。这里有两个链接详细解释了这一点 http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/http://css-tricks.com/return-false-and-prevent-default/

    【讨论】:

      【解决方案2】:

      您可以将 clent 事件放在 a 上吗?现在您不必担心事件传播。

      $('.list_row_input_type.unread a.toggleRead').click(function(e) {
        e.preventDefault();
        toggleRead();
      });
      

      【讨论】:

        猜你喜欢
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        • 2015-10-04
        • 1970-01-01
        • 2016-01-28
        • 2016-05-09
        • 1970-01-01
        相关资源
        最近更新 更多