jQuery为空选择添加元素?

时间:2022-09-05 23:04:47

Why doesn't this work?

为什么不工作呢?

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

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.

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

9 个解决方案

#1


44  

Quoting from the jQuery website:

引用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.

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

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

因此,当您执行.add()时,它不会保存添加的元素,您必须显式地将元素分配给新创建的对象,即

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

#2


12  

The .add() method returns a new jQuery object, so you'd need to overwrite the old one:

add()方法返回一个新的jQuery对象,因此需要覆盖旧的对象:

spans = spans.add( elem );

...or since you're adding DOM elements, you can modify the existing jQuery object with .push().

…或者因为要添加DOM元素,所以可以使用.push()修改现有的jQuery对象。

spans.push( elem );

EDIT: Changed .pushStack() to .push(), though I don't know if .push() is officially supported.

编辑:更改. pushstack () to .push(),尽管我不知道是否正式支持push()。


You could use .pushStack() to add a collection though.

您可以使用. pushstack()添加一个集合。

spans = spans.pushStack( [elem] );

or

spans = spans.pushStack( document.getElementsByTagName('div') );

#3


6  

I guess I don't get what you're asking. If you have an element and you want to add it to a collection, you just use the .add() method just like you've already shown. What confuses some is that this returns a new jQuery object so you would do it like this:

我想我不明白你的要求。如果您有一个元素,并且想要将它添加到集合中,您只需使用.add()方法,就像您已经展示的那样。让人困惑的是它返回了一个新的jQuery对象,所以你会这样做:

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

Of course, something like this would be shorter:

当然,像这样的东西会更短:

var spans = $();
spans = spans.add('#someId');

And, of course, you don't have to start with an empty object. You would just start with:

当然,你不需要从一个空的对象开始。你只需要从:

var spans = $('#someId');

#4


3  

If you're looking to push or add items selected from a jQuery object, you could also do this:

如果您想要推送或添加从jQuery对象中选择的项,也可以这样做:

var $els = $(),
    $someEls = $(".some-els");

$els.push.apply($els, $someEls);

Just another way to do it.

这是另一种方法。

#5


2  

What you actually want to do is use jQuery to it's full potential. You can use selectors to grab and create the collection right away. Your three lines above becomes one line:

实际上,您需要做的是使用jQuery来充分发挥其潜力。您可以使用选择器立即抓取和创建集合。你上面的三行变成了一行:

var spans = $('#someId');

to add more ids to the collection, you can separate them with commas:

要向集合中添加更多的id,可以用逗号分隔它们:

var spans = $('#someId1, #someid2, #someid3');

#6


1  

There may be better ways to do what you're trying, but if you just want to create an empty jQuery object, use this:

可能有更好的方法来完成您正在尝试的工作,但是如果您只想创建一个空的jQuery对象,请使用以下方法:

var $foo = $([]);


Edit: I should clarify - your code actually should work, unless you're using an older version of jQuery, in which case $() would create a collection containing the document object. In newer versions, however, there's nothing wrong with that. The code snippet I pasted above is just something that should work in older versions and newer versions of jQuery.
Edit 2: In response to this portion of the question: "I want to loop through a collection of ids and find the element on the page and add it to the matched set", the following code might be useful:

var ids = ['foo', 'bar', 'baz'],
    selector = $.map(ids, function(i, id) {
        return '#' + id;
    }).join(','),
    $collection = $(selector);

#7


1  

While this doesn't directly answer the question of "how to append to an existing jQuery selection", I have a work-around for this particular use-case.

虽然这不能直接回答“如何附加到现有jQuery选择”的问题,但我对这个特定的用例有一个变通方法。

You can pass an array of DOM elements to jQuery, and it will create a jQuery selection out of them.

您可以将DOM元素数组传递给jQuery,它将从中创建一个jQuery选择。

var spansArray = [];
var elem = document.getElementById('someId');
spansArray.push(elem);
var spans = $(spansArray);

I can't think of any reason why you would need to add each element to the jQuery selection one-at-a-time, as opposed to all-at-once, so this should be a "drop-in-replacement" for your use case. In theory, this must also prove more efficient, as jQuery's .add() is ultimately just calling .push() on some array behind the scenes.

我想不出任何理由,为什么您需要将每个元素添加到jQuery选择一次,而不是一次性的,因此,这应该是您的用例的“插入替换”。从理论上讲,这也必须证明更有效,因为jQuery的.add()最终只是在后台对某些数组调用.push()。

#8


0  

Try

试一试

var spans = $("<span />");
var elem = $("#someId").html();
spans.append(elem).appendTo('#someAnotherId');

instead

而不是

#9


0  

The reason your code doesn't work is because add does not change the collection, it returns a new jQuery object with the new elements in it. If you wanted, you could instead say spans = spans.add(elem);, but what you're doing is unnecessary: the beauty of jQuery is that it makes this sort of imperative programming unnecessary. Look at helloandre's answer for a much easier way to accomplish your goal.

代码不能工作的原因是add不改变集合,它返回一个带有新元素的jQuery新对象。如果您想要,可以改为span = spans.add(elem);但是您所做的是不必要的:jQuery的美丽在于它使这种强制编程变得不必要。看看helloandre的答案,找到一个更容易实现目标的方法。

It's like the following, if this makes sense:

就像下面这样,如果这有意义的话:

var x = [1, 2, 3];
x.concat(4);
console.log(x); // [1, 2, 3] -- concat does not mutate the original array

#1


44  

Quoting from the jQuery website:

引用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.

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

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

因此,当您执行.add()时,它不会保存添加的元素,您必须显式地将元素分配给新创建的对象,即

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

#2


12  

The .add() method returns a new jQuery object, so you'd need to overwrite the old one:

add()方法返回一个新的jQuery对象,因此需要覆盖旧的对象:

spans = spans.add( elem );

...or since you're adding DOM elements, you can modify the existing jQuery object with .push().

…或者因为要添加DOM元素,所以可以使用.push()修改现有的jQuery对象。

spans.push( elem );

EDIT: Changed .pushStack() to .push(), though I don't know if .push() is officially supported.

编辑:更改. pushstack () to .push(),尽管我不知道是否正式支持push()。


You could use .pushStack() to add a collection though.

您可以使用. pushstack()添加一个集合。

spans = spans.pushStack( [elem] );

or

spans = spans.pushStack( document.getElementsByTagName('div') );

#3


6  

I guess I don't get what you're asking. If you have an element and you want to add it to a collection, you just use the .add() method just like you've already shown. What confuses some is that this returns a new jQuery object so you would do it like this:

我想我不明白你的要求。如果您有一个元素,并且想要将它添加到集合中,您只需使用.add()方法,就像您已经展示的那样。让人困惑的是它返回了一个新的jQuery对象,所以你会这样做:

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

Of course, something like this would be shorter:

当然,像这样的东西会更短:

var spans = $();
spans = spans.add('#someId');

And, of course, you don't have to start with an empty object. You would just start with:

当然,你不需要从一个空的对象开始。你只需要从:

var spans = $('#someId');

#4


3  

If you're looking to push or add items selected from a jQuery object, you could also do this:

如果您想要推送或添加从jQuery对象中选择的项,也可以这样做:

var $els = $(),
    $someEls = $(".some-els");

$els.push.apply($els, $someEls);

Just another way to do it.

这是另一种方法。

#5


2  

What you actually want to do is use jQuery to it's full potential. You can use selectors to grab and create the collection right away. Your three lines above becomes one line:

实际上,您需要做的是使用jQuery来充分发挥其潜力。您可以使用选择器立即抓取和创建集合。你上面的三行变成了一行:

var spans = $('#someId');

to add more ids to the collection, you can separate them with commas:

要向集合中添加更多的id,可以用逗号分隔它们:

var spans = $('#someId1, #someid2, #someid3');

#6


1  

There may be better ways to do what you're trying, but if you just want to create an empty jQuery object, use this:

可能有更好的方法来完成您正在尝试的工作,但是如果您只想创建一个空的jQuery对象,请使用以下方法:

var $foo = $([]);


Edit: I should clarify - your code actually should work, unless you're using an older version of jQuery, in which case $() would create a collection containing the document object. In newer versions, however, there's nothing wrong with that. The code snippet I pasted above is just something that should work in older versions and newer versions of jQuery.
Edit 2: In response to this portion of the question: "I want to loop through a collection of ids and find the element on the page and add it to the matched set", the following code might be useful:

var ids = ['foo', 'bar', 'baz'],
    selector = $.map(ids, function(i, id) {
        return '#' + id;
    }).join(','),
    $collection = $(selector);

#7


1  

While this doesn't directly answer the question of "how to append to an existing jQuery selection", I have a work-around for this particular use-case.

虽然这不能直接回答“如何附加到现有jQuery选择”的问题,但我对这个特定的用例有一个变通方法。

You can pass an array of DOM elements to jQuery, and it will create a jQuery selection out of them.

您可以将DOM元素数组传递给jQuery,它将从中创建一个jQuery选择。

var spansArray = [];
var elem = document.getElementById('someId');
spansArray.push(elem);
var spans = $(spansArray);

I can't think of any reason why you would need to add each element to the jQuery selection one-at-a-time, as opposed to all-at-once, so this should be a "drop-in-replacement" for your use case. In theory, this must also prove more efficient, as jQuery's .add() is ultimately just calling .push() on some array behind the scenes.

我想不出任何理由,为什么您需要将每个元素添加到jQuery选择一次,而不是一次性的,因此,这应该是您的用例的“插入替换”。从理论上讲,这也必须证明更有效,因为jQuery的.add()最终只是在后台对某些数组调用.push()。

#8


0  

Try

试一试

var spans = $("<span />");
var elem = $("#someId").html();
spans.append(elem).appendTo('#someAnotherId');

instead

而不是

#9


0  

The reason your code doesn't work is because add does not change the collection, it returns a new jQuery object with the new elements in it. If you wanted, you could instead say spans = spans.add(elem);, but what you're doing is unnecessary: the beauty of jQuery is that it makes this sort of imperative programming unnecessary. Look at helloandre's answer for a much easier way to accomplish your goal.

代码不能工作的原因是add不改变集合,它返回一个带有新元素的jQuery新对象。如果您想要,可以改为span = spans.add(elem);但是您所做的是不必要的:jQuery的美丽在于它使这种强制编程变得不必要。看看helloandre的答案,找到一个更容易实现目标的方法。

It's like the following, if this makes sense:

就像下面这样,如果这有意义的话:

var x = [1, 2, 3];
x.concat(4);
console.log(x); // [1, 2, 3] -- concat does not mutate the original array