ページが最初に読み込まれるとき、次のclick
イベント設定があります (正常に動作します)。
$('#thisIsTheElement').click(function() {
firstFunction();
});
後で(何かが発生した後)、このクリックを別の関数を指すように変更したい
secondFunction();
これを行う最も効率的な方法は何ですか?
バインドを解除して再度バインドする必要がありますか? これは1行で実行できますか?
ページが最初に読み込まれるとき、次のclick
イベント設定があります (正常に動作します)。
$('#thisIsTheElement').click(function() {
firstFunction();
});
後で(何かが発生した後)、このクリックを別の関数を指すように変更したい
secondFunction();
これを行う最も効率的な方法は何ですか?
バインドを解除して再度バインドする必要がありますか? これは1行で実行できますか?
something
考えられる解決策の 1 つは、フラグを使用して、発生したかどうかを追跡することです。
var somethingOccurred = false;
$('#thisIsTheElement').click(function() {
if(somethingOccurred){
secondFunction();
} else {
firstFunction();
}
});
//when something occurs
somethingOccurred = true
別のオプションは次のようなものです。
$('#thisIsTheElement').on('click', firstFunction);
以降:
$('#thisIsTheElement').off('click', firstFunction).on('click', secondFunction);
.one()ドキュメント。
このコードは 2 つの機能を切り替えます。
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
1 回実行され、次回以降は実行されます。secondFunction
function firstFunction() {
alert('First handler: ' + $(this).text());
$(this).on("click", secondFunction);
}
function secondFunction() {
alert('Second handler: ' + $(this).text());
}
$("div").one("click", firstFunction);