简体   繁体   中英

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. HTML code is-

<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-

$( 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. 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()

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

use 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 . which will prevent from multiple triggering your function code.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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