简体   繁体   English

如何防止点击触发jQuery中的多个点击处理程序调用

[英]How to prevent a click from triggering multiple click handler calls in jQuery

I am using jQuery for a list and a div element click. 我使用jQuery的列表和div元素单击。 HTML code is- HTML代码是-

<ul class="list-group">
    <li class="list-group-item">
        <div>
            <div>
                Anything <img id="image_click" src="http://www.neatimage.com/im/lin_logo.gif">
            </div>
            <div>
                More thing
            </div>
        </div>
    </li>
    <li class="list-group-item">Documents</li>        
    <li class="list-group-item">Music</li>
    <li class="list-group-item">Videos</li>
</ul>

And jQuery code is- jQuery代码是-

$( document ).ready(function()
{
    $(".list-group-item").click(function()
    {
        alert($("For list");
    });

    $("#image_click").click(function()
    {
        alert("for image");
    });
});

When I click on a li item, only For list is alerted. 当我单击li项时,仅“ For list”被提醒。 But if I clicked on image, then for image and after that For list is alerted. 但是,如果我单击图像,则对于图像以及此后的列表警报。

What I want is if anyone click on li element, For list should be alerted, but if he clicks on the image, only for image should be alerted, for list should not be alerted. 我要的是,如果有人点击李元素, 对于表应警惕,但如果他点击了图片,只为图像应警惕, 对名单不应该被警告。

It is because of event bubbling , so you stop it by calling Event.stopPropagation() 这是因为事件冒泡 ,所以您可以通过调用Event.stopPropagation()来停止它

$("#image_click").click(function (e) {
    e.stopPropagation();
    alert("for image");
});

use stopPropagation() ; 使用stopPropagation() ; : to stop bubbling event :停止冒泡事件

 $("#image_click").click(function(e)
    {
       e.stopPropagation();
        alert("for image");
    });

Or you can try this code: 或者您可以尝试以下代码:

$(".list-group-item").click(function (e) {
    if(this==e.target)
         alert("for list");
});  

I think this question may help you. 我认为这个问题可能对您有帮助。

If you do not want any action from any action that simply write return false . 如果您不希望任何简单写入的操作中的任何操作,则return false which will prevent from multiple triggering your function code. 这样可以防止多次触发您的功能代码。

 $(".list-group-item").click(function(){
       return false;
    });

$("#image_click").click(function(){
     alert("for image");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM