1

私はこのようにやっています:

$(".classname").bind("keypress",function(){
    alert("event happened");
})

上記と同様のコードで、一度だけ機能します。つまり、最初に入力してEnterをクリックすると機能しますが、次回はまったく反応しません。

$("#id").bind("keypress",function(){
   alert("haiii");
}) 

2 番目のコードは常に機能しますが、最初のコードは 1 回しか機能しません。

また、2 番目のコードが 1 回実行されると、最初のコードは 1 回も実行されません。

解決策は何ですか?ここにはいくつかのルールが欠けていると思います。それらについて調べますので教えていただけますか。ありがとう

4

2 に答える 2

0

イベント バインダーは常に利用可能である必要があります。そうでない場合は、HTML 構造を変更している (ノードの追加または削除) ためです。あなたの場合、実行時にHTMLを動的に変更しているため、使用する必要があります.on()

代わりにこれを試してください.bind()

    $('#id').on({
       keypress: function () { alert("hi"); }
    });

    $('.ClassName').on({
       keypress: function () { alert("hi"); }
    });

    // IF YOU KNOW CLASSNAME ELEMENTS ARE INSIDE A FIXED ELEMENT:

    $('#FixedID').on({
       keypress: function () { alert("hi"); }
    }, '.ClassName');

コーディング スタイルに関しては、イベント ハンドラーとイベントを処理する関数を分離する必要があります。たとえば、これの代わりに、ハンドラーもコードを実行します。

// one function that does everything!!
$(document).ready(function() {
    // bind events
    $('#SomeID').on({

       click: function () {
         // huge wall of code that handles events
       },
       mouseenter: function () {
         // another huuuuuuuge wall of code here
       }
    )};
});

次のようなものが必要です。

$(document).ready(function () {
    BindHandlers();
    DoSomethingElseWithPageInit();
}); 

function BindHandlers() {
// handlers do just the handling of events; easy to see and understand
   $('#SomeID').on({
      click: function (e) { ClickOnSomeID(e); },
      mouseenter: function () { MouseEnterOnSomeID(); }
   )};
}

// here are the functions that process the event
function ClickOnSomeID(e) { ... }
function MouseEnterOnSomeID() { ... }
于 2012-05-21T17:28:25.747 に答える