2

ページが最初に読み込まれるとき、次のclickイベント設定があります (正常に動作します)。

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

後で(何かが発生した後)、このクリックを別の関数を指すように変更したい

secondFunction();

これを行う最も効率的な方法は何ですか?

バインドを解除して再度バインドする必要がありますか? これは1行で実行できますか?

4

3 に答える 3

4

something考えられる解決策の 1 つは、フラグを使用して、発生したかどうかを追跡することです。

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

//when something occurs
somethingOccurred = true
于 2013-08-18T01:20:44.677 に答える
2

別のオプションは次のようなものです。

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

以降:

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

http://jsfiddle.net/xZzMD/

于 2013-08-18T01:59:26.827 に答える
1

デモ

.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);

このコードはfirstFunction1 回実行され、次回以降は実行されます。secondFunction

function firstFunction() {
    alert('First handler: ' + $(this).text());
    $(this).on("click", secondFunction);
}
function secondFunction() {
    alert('Second handler: ' + $(this).text());
}
$("div").one("click", firstFunction);
于 2013-08-18T02:08:49.673 に答える