从jQuery 1.7开始,您应该使用jQuery.fn.on
:
$(staticAncestors).on(eventName, dynamicChild, function() {});
在此之前,推荐的方法是使用
live()
:
$(selector).live( eventName, function(){} );
但是,
live()
在1.7中弃用了
on()
,在1.9中已完全删除。
live()
签名:
$(selector).live( eventName, function(){} );
...可以替换为以下
on()
签名:
$(document).on( eventName, selector, function(){} );
例如,如果您的页面正在动态创建类名称为
dosomething
的元素,则可以将该事件绑定到一个已经存在的父对象(这是问题的小结,您需要绑定的东西已经存在,不需要绑定到动态内容),这可以(也是最简单的选项)是
document
。虽然请记住
document
may not be the most efficient option。
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
绑定事件时存在的任何父项都可以。例如
$('.buttons').on('click', 'button', function(){
// do something here
});
适用于
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>