事件绑定器应始终可用;如果不是,那是因为您正在更改 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() { ... }