如何使用 jQuery 获取 DOM 实时集合?
如何从 jQuery 访问实时 DOM 集合?
以此 HTML 和此 JavaScript 代码为例:
var a = $('#a');
var divs = a[0].getElementsByTagName('DIV');
for(var i=0; divs.length < 20; ) {
a.append($('<div>'+(i++)+'</div>'));
}
它将向
因为 divs
是一个实时集合。jQuery 中是否有任何内容可以替换第二行以获得相同的结果?
var divs = $('#a div');
导致无限循环。
JSFiddle 位于此处。
How do I get access to live DOM collections from jQuery?
Take for example this HTML <div id='a'></div>
and this JavaScript code:
var a = $('#a');
var divs = a[0].getElementsByTagName('DIV');
for(var i=0; divs.length < 20; ) {
a.append($('<div>'+(i++)+'</div>'));
}
It will append 20 div children to <div id='a'>
because divs
is a live collection.
Is there anything in jQuery that I could replace the second line with to get the same result?
var divs = $('#a div');
results in infinite loop.
JSFiddle is here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果
#a
已经包含 div:这与上面的代码等效。
In case
#a
already contains divs:That would be equivalent to the code above.
Live Collections - 真正的集合,不是现代 jquery 可以返回的东西。
此外,旨在在不久的将来取代 getElementsByTagName、getQuerySelectorAll 的现代方法也返回静态集合。
这就是您所提出的问题的答案。
至于你真正想问的问题,其他用户已经尝试为你提供一些帮助。
Live Collections - the true ones, are not something which can be returned by modern jquery.
Moreover, modern method which is intended to replace in nearest future getElementsByTagName, getQuerySelectorAll also return a static collection.
This is the answer to question you've stated.
As for the question you've really wanted to ask, other users already tried to provide you some help.
每次选择该元素,都会创建一个新的 jQuery 对象。我认为这是元素发生变化的唯一方法。
编辑:
或者这个:
或者这个,只有一个选择器:
Select the element each time, this will create a new jQuery object. Which I think it the only way if the element is changing.
EDIT:
Or this:
Or this, just one selector:
那是不可能的。
不过,这与示例代码具有相同的效果:
http://jsfiddle.net/mathias/Af538/
更新: 如果代码需要定期重复,您可以使用如下内容:
http://jsfiddle.net/mathias/S5C6n/
That’s not possible.
This has the same effect as your example code, though:
http://jsfiddle.net/mathias/Af538/
Update: If the code needs to be repeated periodically, you could use something like this:
http://jsfiddle.net/mathias/S5C6n/
总是 20 div 孩子吗?
使用下面的不是更好吗
Is it always 20 div children ?
Isn't it better to use the following
您正在寻找的语法是:
由于 ID 应该是唯一的,您可以这样做:
The syntax you're looking for is:
Since IDs are supposed to be unique, you could just do: