自jquery 1.7起
你应该使用
jQuery.fn.on
:
$(staticAncestors).on(eventName, dynamicChild, function() {});
在此之前
建议的方法是
live()
:
$(selector).live( eventName, function(){} );
然而,
LIVER()
在1.7中被否决,赞成
on()
,并在1.9中完全移除。这个
LIVER()
签名:
$(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>