将客户端事件绑定到不同的功能

时间:2013-08-18 01:06:33

标签: jquery

最初加载页面时,我有以下click事件设置(工作正常):

$('#thisIsTheElement').click(function() {
  firstFunction();
});

稍后(发生某些事情后)我想更改此点击以指向名为

的其他功能
secondFunction();

最有效的方法是什么?

我应该再绑定并再绑定吗?这可以在一行中完成吗?

3 个答案:

答案 0 :(得分:4)

一种可能的解决方案是使用标记来跟踪something是否已发生

var somethingOccurred = false;
$('#thisIsTheElement').click(function() {
    if(somethingOccurred){
        secondFunction();
    } else {
        firstFunction();
    }
});

//when something occurs
somethingOccurred = true

答案 1 :(得分:2)

另一种选择可能是这样的:

$('#thisIsTheElement').on('click', firstFunction);

后来:

$('#thisIsTheElement').off('click', firstFunction).on('click', secondFunction);

http://jsfiddle.net/xZzMD/

答案 2 :(得分:1)

DEMO

.one()文档。

此代码将在两个函数之间切换。

function firstFunction() {
    alert('First handler: ' + $(this).text());
    $(this).one("click", secondFunction);
}
function secondFunction() {
    alert('Second handler: ' + $(this).text());
    $(this).one("click", firstFunction);
}
$("div").one("click", firstFunction);

此代码将一次运行firstFunction,下一次运行secondFunction

function firstFunction() {
    alert('First handler: ' + $(this).text());
    $(this).on("click", secondFunction);
}
function secondFunction() {
    alert('Second handler: ' + $(this).text());
}
$("div").one("click", firstFunction);