简体   繁体   中英

Jquery: how to prevent running multiple times?

Sorry for my English, I'm not native English speaker.

I have problem with my code. I have on page something like this:

 $('#hook label').on('click', function() { console.log('ok'); icon = $(this).next('input').val(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="hook"> <label><input> <img src="http://placehold.it/35x35" ></label> <label><input> <img src="http://placehold.it/35x35" ></label> <label><input> <img src="http://placehold.it/35x35" ></label> <label><input> <img src="http://placehold.it/35x35" ></label> </div> 

And this code is running twice if I click on image, but only one when I click on input or label element. How can I prevent to running this twice?

Here is example: http://jsfiddle.net/00akgoe7/2/

It's because of the default behavior of label. To stop that, you need to tell to the event object to stop is default behavior like this:

$('#hook label').on('click', function(ev) {
    ev.preventDefault();
    console.log('ok');
    icon = $(this).next('input').val();
});

Clicking on a label associeted with the for attribute or inside the label, focus the input with a "fake" click event. This is why you get the event twice since by extension, if you click the input, you click the label (the parent) also.

It's two times because when you click on the label it send a click event also to the input and the new event bubbles back to the label . It's tricky :)

It's in all browsers for a better form usability.

So the another possible solution is:

$('label').click(function(e) {
    if (e.target.tagName === "LABEL") {
        alert("!! here")
    }
});

Try it live: http://jsfiddle.net/8qffhwm3/2/

You just need to add a preventDefault().

$('#hook label').on('click', function(e) {
    e.preventDefault();
    console.log('ok');
});

I expect that it help you.

If you want prevent from the event being fired twice, you can use the 'mousedown' event handler. It will just be triggered once, as it is not triggered by standard by clicking the label.

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