简体   繁体   English

如何再次绑定按钮的click事件

[英]how to bind again the click event for the button

I have a button on which i am attaching a click event. 我有一个按钮,上面附有一个点击事件。 I have to unbind it after i click on it, and later on in my code i need to bind that click event on it again. 单击它后,我必须取消绑定它,然后在我的代码中,我需要再次将其单击事件绑定。 I tried binding it again but that does not works. 我尝试再次绑定它,但这不起作用。 I can't use jquery 'live'. 我不能使用jQuery的“活”。 Is there any way to create a custom bind function on click event and then again call it ? 有什么方法可以在click事件上创建自定义绑定函数,然后再次调用它?

$(".submitButton").click(function(e){
    //some functionality on click
    $(".submitButton").unbind('click');
});

//somewhere ahead in my code 
$(".submitButton").bind('click');

Apparently this isn't working. 显然这是行不通的。 Is there any way to tackle this ? 有什么办法解决这个问题?

define your listener somewhere else: 在其他地方定义您的监听器:

function clickHandler() {
    //some functionality on click
    $(".submitButton").unbind('click', clickHandler);
}

$(".submitButton").bind('click', clickHandler);

//somewhere ahead in my code 
$(".submitButton").bind('click', clickHandler);

When you use .bind() to bind an event handler it expects a function to be passed as well, since that's what will be executed when the event fires. 当您使用.bind()绑定事件处理程序时,它也希望传递一个函数,因为这将在事件触发时执行。 Don't use an anonymous function, instead declare a named function and pass a reference to that when binding. 不要使用匿名函数,而是声明一个命名函数并在绑定时传递对该函数的引用。

function handleClick(e){
    //some functionality on click
    $(".submitButton").unbind('click');
}

$(".submitButton").click(handleClick);

// somewhere else in your code (in reaction to some other event)
$(".submitButton").click(handleClick);

Your .bind call doesn't seem correct. 您的.bind呼叫似乎不正确。 You haven't specified a callback. 您尚未指定回调。

So start by writing a function: 因此,首先编写一个函数:

function handleButtonClick() {
    //some functionality on click
    $(this).unbind('click');
}

Notice that inside the handler I am unbinding $(this) which is the element being clicked and not all elements with class="submitButton" . 注意,在处理程序内部,我正在取消绑定$(this) ,这是被单击的元素,而不是具有class="submitButton"所有元素。 and then: 接着:

$('.submitButton').bind('click', handleButtonClick);

and then later when you want to rebind: 然后稍后要重新绑定时:

$('.submitButton').bind('click', handleButtonClick);

and so on. 等等。

You can use jQuery.one() . 您可以使用jQuery.one() Please refer below code. 请参考下面的代码。

$(".submitButton").one('click', clickHandler);

The first form of this method is identical to .bind(), except that the handler is unbound after its first invocation. 此方法的第一种形式与.bind()相同,除了处理程序在首次调用后未绑定。

you can call it or bind it whenever it necessary. 您可以在必要时调用它或绑定它。

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

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