イベント バインダーは常に利用可能である必要があります。そうでない場合は、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() { ... }