前端:用on对动态生成的元素绑定事件
由于一般的事件注册仅对已经存在的元素有效,所以对于未来生成的元素注册事件不能用一般的方式。
在jquery1.8及以前可以用live
方法,1.9之后用on
,但并不是简单的替换,因为参数不同。
.live(events, function)
should map to:
.on(eventType, selector, function)
The selector is very important! If you do not need to use this for any reason, set it to null
.
Migration Example 1:
before:
$('#mainmenu a').live('click', function)
after, you move the child element (a
) to the .on()
selector:
$('#mainmenu').on('click', 'a', function)
Migration Example 2:
before:
$('.myButton').live('click', function)
after, you move the element (.myButton
) to the .on()
selector, and find the nearest parent element (preferably with an ID):
$('#parentElement').on('click', '.myButton', function)
If you do not know what to put as the parent, body
always works:
$('body').on('click', '.myButton', function)