事件绑定动态创建的元素? [英] Event binding on dynamically created elements?

查看:164
本文介绍了事件绑定动态创建的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,我在循环遍历页面上的所有选择框,并绑定一个 .hover 事件给他们做一点点与他们的



这种情况发生在页面准备就绪并且工作正常。



我遇到的问题是,在初始循环后,通过Ajax或DOM添加的任何选择框都不会有事件绑定。



我发现这个插件( jQuery实时查询插件),但在我添加之前另一个5k到我的页面与一个插件,我想看看有没有人知道一个方法来做到这一点,或者直接使用jQuery或另一个选项。

解决方案

截至jQuery 1.7 ,您应该使用 jQuery.fn.on

  $(staticAncestors).on(eventName,dynami cChild,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).on('mouseover mouseout','.dosomething',function(){
//你想要什么当鼠标悬停和鼠标移动
//发生在匹配'.dosomething'
}的元素时发生;

事件绑定时存在的任何父对象都可以。例如

  $('。buttons')。on('click','button',function(){
//在这里做某事
});

将适用于

 < div class =buttons> 
<! - < button> s,动态生成并在此添加 - >
< / div>


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.

解决方案

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, often document.

$(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>

这篇关于事件绑定动态创建的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆