jQuery添加元素到空选择? [英] jQuery add elements to empty selection?

查看:185
本文介绍了jQuery添加元素到空选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不工作?

var spans = $();
var elem = document.getElementById('someId');
spans.add(elem);

从空集合开始并添加元素的正确方法是什么?
我想循环遍历一个ids的集合,并找到页面上的元素并将其添加到匹配的集合。

What is the proper way to start off with an empty collection and add elements to it? I want to loop through a collection of ids and find the element on the page and add it to the matched set.

推荐答案

jQuery网站引用:


给定一个表示一组DOM元素的jQuery对象, .add()方法从这些元素的联合构造一个新的jQuery对象,

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() 它不会保存添加的元素,您必须显式地将元素分配给新创建的对象,即

Hence, when you do .add() it will not save the added elements, you would have to explicitly assign the element to the newly created object i.e

var $elements = $('.elements');
$elements = $elements.add($('#anotherelement'));

这篇关于jQuery添加元素到空选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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