为什么这不起作用?
var spans = $();
var elem = document.getElementById('someId');
spans.add(elem);
从空集合开始并向其中添加元素的正确方法是什么? 我想循环遍历 ids 集合并找到页面上的元素并将其添加到匹配的集合中。
最佳答案
引自jQuery website :
Given a jQuery object that represents a set of DOM elements, the
.add()
method constructs a new jQuery object from the union of those elements and the ones passed into the method.
因此,当您这样做时.add()
它不会保存添加的元素,您必须显式地将元素分配给新创建的对象,即
var $elements = $('.elements');
$elements = $elements.add($('#anotherelement'));
关于collections - jQuery 添加元素到空选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7533929/