仅使用 jQuery 添加一次 OnClick 处理程序 - 即使再次调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9970358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:30:50  来源:igfitidea点击:

Add an OnClick handler with jQuery only once - even if called again

jquery

提问by msigman

If I assign a handler to the OnClick event of an element twice, the handler will be executed twice. But I want to change this so even if I assign it twice, the handler will only execute one time.

如果我将一个处理程序分配给一个元素的 OnClick 事件两次,该处理程序将被执行两次。但我想改变这一点,所以即使我分配了两次,处理程序也只会执行一次。

Nonsensical example to demonstrate issue:

演示问题的无意义示例:

$('.button').click(
    function(){
       alert('here');
});
$('.button').click(
    function(){
       alert('here');
});

So I've added the handler twice. Now when I click an element with that class, I'd get two alert boxes.

所以我已经添加了两次处理程序。现在,当我单击具有该类的元素时,会得到两个警告框。

The question is, how do I restrict it so I would only get one alert box?

问题是,我如何限制它以便我只能收到一个警报框?

回答by powerbuoy

If .one()is in fact what you're after (removing the event handler after it has been triggered once) then I believe that's the correct answer. If not, you can unbind the event before binding it:

如果.one()实际上是您所追求的(在触发一次后删除事件处理程序),那么我相信这是正确的答案。如果没有,您可以在绑定之前解除绑定事件:

var myEventHandler = function () {alert('hello')};
$('a').unbind('click', myEventHandler);
$('a').bind('click', myEventHandler);

Should work.

应该管用。

Edit: since this reply keeps getting up votes, I'll add another (better in most cases) solution that will work at least in the OP's case. When dealing with dynamically added content simply use jQuery's on()on a parent element instead of applying the event handler directly on the element.

编辑:由于此回复不断获得投票,我将添加另一个(在大多数情况下更好)解决方案,该解决方案至少在 OP 的情况下有效。处理动态添加的内容时,只需on()在父元素上使用 jQuery ,而不是直接在元素上应用事件处理程序。

http://api.jquery.com/on/

http://api.jquery.com/on/

回答by Miquel

a little trick that can help:

一个可以帮助的小技巧:

jQuery(".button:not(.clickadded)").click(function(){

     alert('here');

).addClass("clickadded");

回答by Larry Battle

Use one. http://api.jquery.com/one/

使用一个。 http://api.jquery.com/one/

$( ".button" ).one( 'click', function(){
    alert( '....' )
});

回答by leepowers

To have the events triggered only once, bind them only once. When dynamically adding elements, bind the event handler to the parent element using on():

要让事件只触发一次,只需将它们绑定一次。动态添加元素时,使用以下方法将事件处理程序绑定到父元素on()

See this jsfiddle:

看到这个jsfiddle

<div id="container">
 <p>Paragraph #1</p>
</div>

<div>
 <button id="add">Add Elements</button>
</div>

<script type="text/javascript">
 var n = 1;
 $('#add').click(function() {
   $('#container').append('<p>Paragraph #' + ++n + '</p>');
 });
 $('#container').on('click', 'P', function() {
   alert($(this).text());
 });
</script>

Note how the event handlers are registered with on()only once. The code that dynamically adds elements does not register the event handlers.

请注意事件处理程序如何on()仅注册一次。动态添加元素的代码不注册事件处理程序。

回答by Justin Ipson

You can also remove any existing click events in the function with function off('click'):

您还可以使用函数 off('click') 删除函数中任何现有的点击事件:

$('.button').off('click').click(function() {
    ...
});

回答by Muhammad Hewedy

I solved it by a flag, I know it is not the best by just an idea

我通过一个标志解决了它,我知道这不是最好的一个想法

if (!alreadyBound) {
     $('.button').bind('click', submitEvtHandler);
     alreadyBound = true;
}

回答by areve

Here is a method I'm using, similar to Miquel's method in some ways.

这是我正在使用的一种方法,在某些方面类似于 Miquel 的方法。

$.prototype.once = function() {
    var ret = this.not(function() {
        return this.once;
    });
    this.each(function(id, el) {
        el.once = true;
    });
    return ret;
};

Use it like this,

像这样使用它,

$('#footer')
    .once()
    .click(function(){
        console.log('click the footer');
    });

Once also supports a parameter so you can have different types

一次也支持一个参数,所以你可以有不同的类型

回答by Dips

I think there is no point to add function twice. However if you have to then you can do add return falseto one of the function.

我认为没有必要添加两次功能。但是,如果您必须这样做,您可以添加return false到该功能之一。

$('.button').click(
    function(){
       return false;
       alert('here');
});
$('.button').click(
    function(){
       alert('here');
});?