单击“子级"元素时,忽略“父级onClick"事件 [英] Ignore Parent onClick event when Child element is clicked

查看:343
本文介绍了单击“子级"元素时,忽略“父级onClick"事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅- http://www.bootply.com/dR7fxjP1bk

通过单击任何div.rows(可称为该父级),将激活onClick事件,出于演示目的,会弹出警报.

在该行中,单击信息"(橙色按钮)(让我们称呼这个孩子)时,手风琴会折叠,但是问题是父母警报会触发.

我需要信息"按钮不触发警报,只有在单击其他任何位置时,警报才会出现.

我已经尝试了多种方法,例如使用(e)stopPropagation .on .off调用等...我不是最好的jquery家伙,因此需要一些帮助以使其正常工作-并帮助我学习一些东西!

<div class="row ticket-selector" onclick="alert('Hello World!');">
    <a data-toggle="collapse" data-parent="#ticket-panel" href="#collapseOne" class="tickets-more"><span class="halflings info-sign orange"></span></a>
</div>

以上内容是最基本的-但请参阅以便更好地理解- http://www.bootply.com/dR7fxjP1bk

解决方案

该想法是删除onclick=""处理程序,将其值保存在另一个字段中,然后在自定义click事件处理程序中执行(评估)值:

示例代码.

$(document).ready(function()
{
    var elements = $(".ticket-selector");
    elements.each(function()
    {
        var handler = $(this).attr('onclick');
        $(this).data('click', handler);
    });
    elements.attr('onclick', '');
    elements.click(function(e)
    {
        if (!$(e.target).hasClass("info-sign"))
        {
            eval($(this).data('click'));
        }
    });
});

Please see - http://www.bootply.com/dR7fxjP1bk

By clicking any of the div.rows (lets call this parent), an onClick event is activated, for demo purposes an alert pops up.

Within the row an accordion collapses when the "info" (orange button) is clicked (lets call this child), but the problem is that the parents alert triggers.

I need the info button not to trigger the alert, only when anywhere else is clicked the alert appears.

I've tried various ways such as using (e)stopPropagation .on .off calls etc... I'm not the best jquery guy so need a little help getting this to work - and also help me learn something!

<div class="row ticket-selector" onclick="alert('Hello World!');">
    <a data-toggle="collapse" data-parent="#ticket-panel" href="#collapseOne" class="tickets-more"><span class="halflings info-sign orange"></span></a>
</div>

The above is the jist - but see for better understanding - http://www.bootply.com/dR7fxjP1bk

解决方案

The idea is to remove onclick="" handler saving its value in another field and then to execute (evaluate) value in custom click event handler:

Example code.

$(document).ready(function()
{
    var elements = $(".ticket-selector");
    elements.each(function()
    {
        var handler = $(this).attr('onclick');
        $(this).data('click', handler);
    });
    elements.attr('onclick', '');
    elements.click(function(e)
    {
        if (!$(e.target).hasClass("info-sign"))
        {
            eval($(this).data('click'));
        }
    });
});

这篇关于单击“子级"元素时,忽略“父级onClick"事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆