,如果你使用jQuery,您要使用on()
将事件处理程序绑定到的元素,而不是指定它们内嵌
$('#mydiv').on('focus', function() {
alert('hello');
});
$('#mydiv').on('focus', function() {
if (something === somethingelse) {
alert('world');
}
});
或组合成一个处理函数,在这种情况下,似乎是合理的
$('#mydiv').on('focus', function() {
alert('hello');
if (something === somethingelse) {
alert('world');
}
});
当直列指定他们为你所做的一切,只有一个事件处理程序可以这样,如果你要绑定绑定到事件多个事件处理程序,您需要弯曲一个事件处理程序限制来处理此问题或使用其他方法,如DOM Level 2 events或其上的抽象(如jQuery的on()
函数)。
当您绑定处理程序的元素存在于DOM中时,事件处理程序需要绑定。要做到这一点,你可以使用jQuery的ready()
功能
// bind an event handler to the "ready" event on the document
$(document).ready(function() {
// ..... here
});
或简写
$(function() {
// ..... here
});
需要之前,IE 9 – 2013-05-10 10:25:24
的Internet Explorer版本的IE支持的测试,你必须使用'attachEvent'而比标准的'addEventListener'。 – 2013-05-10 10:26:46