如何在jQuery中检测新元素的创建? [英] How to detect new element creation in jQuery?
问题描述
假设我有以下代码返回页面上锚元素的数量:
Lets say I have the following code that returns number of anchor elements on a page:
function getLinkCount() {
alert("Links:" + $("a").length);
}
如果我打电话给文件就绪,它会按预期工作。但是,如果现在通过javascript动态地将新链接插入到页面中,我怎样才能获得再次运行链接计数器功能的通知? (我无法控制可以创建新链接的脚本。)
If I call in on document ready it would work as expected. But what if now a new link gets inserted into a page dynamically through javascript, how can I get notified to run link counter function again? (I have no control over a script that could create a new link).
基本上我正在寻找类似于 live()的东西
只会看到元素创建事件,例如:
Basically I am looking for something similar to live()
only that would be watching element creation event, something like:
$("a").live("create", getLinkCount);
在创建新元素时会触发。
that would trigger when a new element is created.
推荐答案
您可以使用 .livequery()
插件为此,它为每个元素运行,包括新元素,如下所示:
You can use the .livequery()
plugin for this, it runs for each element, including new ones, like this:
$("a").livequery(getLinkCount);
但是,这个插件是过时的,不推荐用于当前版本的jQuery。
However, this plugin is out-of-date and is not recommended for current versions of jQuery.
在创建元素时通常更容易做到这一点,例如,如果你在AJAX请求之后这样做, .ajaxComplete()
处理程序可能是一个好地方,例如:
It's usually easier to do this when you create the elements though, for example if you're doing it after AJAX requests, the .ajaxComplete()
handler may be a good place, for example:
$(document).ajaxComplete(getLinkCount);
这将在每次请求后运行,因为您通常在中创建元素成功
处理程序,当这个完整的处理程序运行时,它们已经存在。
This would run after each request, and since you normally create elements in your success
handler, they would already be present when this complete handler runs.
这篇关于如何在jQuery中检测新元素的创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!