1

私は次のコードを持っています:

$("#another").click(function() {
    $('#another').replaceWith('<a id="another" class="btn btn-primary btn-mini disabled"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>');
    $.get('another.php', { 'cycle' : i }, function(data) {
        $('tbody').append(data);
        $("#another").replaceWith('<a id="another" class="btn btn-primary btn-mini"><i class="icon-plus icon-white"></i>&nbsp;Load another cycle</a>');
    });
    i++;
});

別の ID を持つ要素をクリックすると、一度読み込まれます。ワンクリックすると、再び機能しなくなります。

4

3 に答える 3

2

ノードを、イベント リスナーを持たないノードに置き換えています。

基本的にクリックする前に

[#another]
    ^
    |
[clickListener]

次に、別のボタンを作成します ( <a id="another" class="btn btn-primary btn-mini disabled"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>)

[#another]     [#another](2)
    ^
    |
[clickListener]

次に、レイアウト内の最初のものを 2 番目のものに置き換えます。

[#another]               [#another](2)
    ^
    |
[clickListener]

ちょっと待って、私のモデルでは何も変わっていません。これは、クリック リスナーがその最初のオブジェクト (表示されなくなった) にリンクされているのに対し、表示されているオブジェクトはまだそこにあるためです。


コードごとに、これはどういう意味ですか? これは単に、イベント リスナーをそこにアタッチする必要があることを意味します。これが私がそれをした方法です

var onClick=function(){
    $('#another').replaceWith('<a id="another" class="btn btn-primary btn-mini disabled"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>')
    .click(onClick); // <--- this is the important line!

    $.get('another.php', { 'cycle' : i }, function(data) {
        $('tbody').append(data);
        $("#another").replaceWith('<a id="another" class="btn btn-primary btn-mini"><i class="icon-plus icon-white"></i>&nbsp;Load another cycle</a>');
    });
    i++;
}

$("#another").click(onClick);
于 2012-04-10T01:45:03.687 に答える
1

同じイベントハンドラーを使用して、同じボタンを保持することをお勧めします。テキストを動的に変更して増分するだけiです。これを試して:

// Execute in a closure to isolate all the local variables
// Optional, but I like doing this when counter variables are involved
(function() {
    var button = $("#another");
    var a = button.find("a");
    var i = 1;

    button.click(function() {
        // Replace the inner html, not the entire element
        a.html("<i class='icon-refresh icon-white'</i>&nbsp;Loading...");
        $.get("another.php", {
            cycle: i
        }, function(data) {
            $("tbody").append(data);
            a.html("<i class='icon-plus icon-white'></i>&nbsp;Load another cycle");            
            i++;
        });
    });
})();

このメソッドの利点は、DOM操作が少なく、インラインJavaScriptがなく、グローバル関数や変数がないことです。外側のマークアップが同じである場合、ボタンを毎回破棄して再作成する理由は実際にはありません。

于 2012-04-10T01:50:36.573 に答える
1

要素を別の要素に置き換えると、すべてのリスナーが削除されます。これを回避するには、リスナーを新しい要素に再度追加します

$('#another').bind('click', function() {
  //do something
});

onclickまたは、コードを関数に移動して、要素に属性を追加します。

onclick="my_function();"

現在のJavaScriptでは、次のようになります

$('#another').replaceWith('<a id="another" class="btn btn-primary btn-mini disabled" onclick="my_function();"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>');
于 2012-04-10T01:40:32.843 に答える