是否有一个jquery事件会在新节点插入到dom时触发? [英] Is there a jquery event that fires when a new node is inserted into the dom?

查看:102
本文介绍了是否有一个jquery事件会在新节点插入到dom时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个事件jquery在dom元素插入到dom时触发?

例如,可以说我通过ajax加载了一些内容并将其添加到DOM中,并且在其他一些javascript中,我可以使用.live()添加一个事件,以便当将与特定选择器匹配的事件添加到DOM时,事件触发元件。类似于$(document).ready(),但对于动态添加到DOM的内容。



我在做什么:

  $('。myClass')。live('ready',function(){
alert('。myClass added to dom');
});

如果jquery不支持这样的事情,那么有没有另一种方式可以实现这个功能而不需要修改该代码实际上做了初始dom操作?

.livequery()插件仍然适用于这种小众需求,如下所示:

  $('。myClass')。livequery(function(){
alert('。myClass added to dom');
}) ;

如果你只传递一个像上面这样的回调函数,它会运行它找到的每个新元素,包括最初和添加时。在函数中,这个引用刚添加的元素。



.live() 侦听冒泡的事件,所以不适合这个元素被添加的情况,在这方面, .livequery() (该插件)并非完全被替换为 .live() 为核心,只有事件冒泡部分(大部分)是。


Is there an event jquery fires on a dom element when it is inserted into the dom?

E.g. lets say I load some content via ajax and add it to the DOM and in some other piece of javascript I could add an event using .live() so that when an event matching a specific selector is added to the DOM the event fires on said element. Similar to $(document).ready() but on content that is added to the DOM dynamically.

What I am dreaming of:

$('.myClass').live('ready', function() {
    alert('.myClass added to dom');
});

If jquery doesn't support such a thing then is there another way I could achieve this functionality without modifying the code that actually does the initial dom manipulation?

解决方案

The .livequery() plugin still serves this niche need, like this:

$('.myClass').livequery(function() {
  alert('.myClass added to dom');
});

If you pass it just a callback function like above, it'll run for each new element it finds, both initially and as they're added. Inside the function this refers to the just-added element.

.live() listens for events that bubble, so doesn't fit this "when elements are added" situation, in that respect, .livequery() (the plugin) wasn't completely replaced by the addition of .live() to core, only the event bubbling portion (for the most part) was.

这篇关于是否有一个jquery事件会在新节点插入到dom时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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