简体   繁体   English

jQuery:如何防止多次运行?

[英]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/ 例如: http : //jsfiddle.net/00akgoe7/2/

It's because of the default behavior of label. 这是由于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. 单击与for属性关联的标签,或在标签内部,将输入与“假”点击事件一起聚焦。 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 . 这是两次,因为当您单击标签时,它还会将click事件发送到输入 ,而新事件会冒泡返回到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/ 尝试一下: http : //jsfiddle.net/8qffhwm3/2/

You just need to add a preventDefault(). 您只需要添加一个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. 如果要防止事件被触发两次,则可以使用“ mousedown”事件处理程序。 It will just be triggered once, as it is not triggered by standard by clicking the label. 它只会被触发一次,因为它不是通过单击标签由标准触发的。

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

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