最初加载页面时,我有以下click
事件设置(工作正常):
$('#thisIsTheElement').click(function() {
firstFunction();
});
稍后(发生某些事情后)我想更改此点击以指向名为
的其他功能secondFunction();
最有效的方法是什么?
我应该再绑定并再绑定吗?这可以在一行中完成吗?
答案 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);
答案 2 :(得分:1)
.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);