我有一些代码,我在循环遍历页面上的所有选择框,并将.hover事件绑定到他们,以便在mouse on/off进行一点点的宽度调整。
这在页面准备就绪并且工作正常。
我遇到的问题是,在初始循环之后,通过Ajax或DOM添加的任何选择框都不会被绑定。
我发现这个插件( jQuery Live Query Plugin ),但是在我用另外一个插件添加另外5k的页面之前,我想看看有没有人知道如何使用jQuery直接或者另一个选项。
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off.
This happens on page ready and works just fine.
The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.
I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
最满意答案
从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).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>As of jQuery 1.7 you should use jQuery.fn.on:
$(staticAncestors).on(eventName, dynamicChild, function() {});Prior to this, the recommended approach was to use live():
$(selector).live( eventName, function(){} );However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:
$(selector).live( eventName, function(){} );... can be replaced with the following on() signature:
$(document).on( eventName, selector, function(){} );For example, if your page was dynamically creating elements with the class name dosomething you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document. Though bear in mind 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' });Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){ // do something here });would apply to
<div class="buttons"> <!-- <button>s that are generated dynamically and added here --> </div>更多推荐
发布评论