如何创建一个准备追加的空的、非空的 jQuery 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5598494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:27:05  来源:igfitidea点击:

How to create an empty, non-null jQuery object ready for appending?

jquerydom

提问by Tony_Henrich

I want to append some html to an empty non null jQuery object only in the loop but it's not working unless I create an object and add an html tag during creation. How can I create an empty jQuery object and be able to add html to it later on?

我只想在循环中将一些 html 附加到一个空的非空 jQuery 对象,但除非我创建一个对象并在创建过程中添加一个 html 标记,否则它不起作用。我怎样才能创建一个空的 jQuery 对象并能够在以后向它添加 html?

//var $new = $().add("");  //can't use this object in the loop
//var $new = $([]);        //can't use this object in the loop
//var $new = $();        //can't use this object in the loop
//var $new = $("#nonexistingelement"); //can't use this object in the loop
var $new = $().add("<tr>");  //works but I don't want to add any html at this point. 

$.each(.....)
  {
    $new.append("<sometag>");

});

alert($new.html());  //should display some html

Addition:http://jsfiddle.net/vfPNT/

另外:http://jsfiddle.net/vfPNT/

采纳答案by Tony_Henrich

I couldn't find another way so I started with the <tr>. Removing the <tr>while keeping the contents didn't work properly and that's why I posted the question. So, instead, I created a new jQuery selection by selecting all the <sometag>'s which were inside the <tr>and threw away $new.

我找不到其他方法,所以我从<tr>. <tr>在保留内容的同时删除无法正常工作,这就是我发布问题的原因。因此,相反,我通过选择所有<sometag>'s which were inside the <tr>并丢弃 $new创建了一个新的 jQuery 选择。

var $new = $().add("<tr>");  

$.each(.....)
  {
    $new.append("<sometag>");

});
$new.append("</tr>");
$newObject = $('sometagt', $new)
..... do more work using $newObject

回答by Shog9

Your problem here is that there aren't "null" jQuery objects that can't be appended to and "empty" ones that can be. You've already identified several ways to create an empty one, and while there may be more, it doesn't matter - what you're trying to do simply won't do what you expect it to, no matter howyou start off, because...

这里的问题是,没有不能附加的“空”jQuery 对象和可以附加的“空”对象。您已经确定了几种创建空方法的方法,虽然可能还有更多方法,但这并不重要 - 无论您如何开始,您尝试做的事情都不会做您期望的事情, 因为...

...append()modifies the DOM, not the jQuery object. And an empty jQuery object has no DOM! Tomalak had the right idea, though you may not have understood it.

...append()修改 DOM,而不是 jQuery 对象。一个空的 jQuery 对象没有 DOMTomalak 的想法是正确的,尽管您可能没有理解。

I'm going to make three observations about jQuery that you're probably already aware of, but which are useful in understanding the remainder of this answer and therefore may benefit future readers:

我将对 jQuery 提出三个您可能已经知道的观察结果,但它们对于理解本答案的其余部分很有用,因此可能会使未来的读者受益:

  1. A jQuery object is fundamentally a setof DOM elements.
  2. Some jQuery methods operate on the set, and some operate on the nodes inthe set.
  3. Some jQuery methods operate only on (or retrieve information only from) the firstnode added to the set.
  1. jQuery 对象基本上是一DOM 元素。
  2. 一些 jQuery 方法对集合进行操作,而另一些则对集合的节点进行操作。
  3. 某些 jQuery 方法仅对添加到集合中的第一个节点进行操作(或仅从中检索信息)。

With these three observations in mind, let's consider your example:

考虑到这三个观察结果,让我们考虑您的示例:

// 1. create an empty set somehow (doesn't matter how)
var $new = $();

// 2. iterate over something
$.each( ..., function( ... )
{
  // 3. construct a DOM fragment from HTML, and append it
  $new.append("<sometag>"); 
});

// 4. try to display HTML corresponding to the jQuery object
alert($new.html());  

In this example, step #3 will fail to do anything useful because the purpose of append()is to take whatever DOM elements it is given and append them as children to each DOM element in the set. Since $newis an emptyset, there are no elements to append to, and... nothing happens. Step #1 is working just fine - but by creating a set without any DOM elements in it, you've set yourself up to fail when you try to use methods that exist to modify the DOM! Reference Observation #2... to modify the set, you need to call a method that actually operateson the set.

在这个例子中,第 3 步将无法做任何有用的事情,因为它的目的append()是获取给定的任何 DOM 元素,并将它们作为子元素附加到集合中的每个 DOM 元素。由于$new是一个集,因此没有要附加的元素,并且……什么也没有发生。步骤 #1 工作得很好 - 但是通过创建一个没有任何 DOM 元素的集合,当你尝试使用现有的方法来修改 DOM 时,你已经让自己失败了!参考观察#2...修改集合,需要调用一个实际操作集合的方法。

Ok, so let's say we use the set modificationmethod add()instead:

好的,假设我们改用set 修改方法add()

  $new = $new.add("<sometag>");

Now we're good, right? Each pass through the loop will create a new jQuery object consisting of the previous set + a newly-created element. Well...

现在我们很好,对吧?每次循环都会创建一个新的 jQuery 对象,该对象由前一个集合 + 一个新创建的元素组成。好...

...this will just cause step #4 to do something odd. See, html()is one of those methods I mentioned in Observation #3 - it operates only on the first elementin the set. So instead of a sequence ("<sometag><sometag><sometag>...") you're only gonna get a HTML representation of the element created on the first pass through the loop ("<sometag>"). Except... You're not even going to get that, because html()creates a representation of the element's children- so what you're reallygoing to end up with is ""...

...这只会导致第 4 步做一些奇怪的事情。看,这html()是我在观察 #3 中提到的方法之一——它只对集合中的第一个元素进行操作。因此,"<sometag><sometag><sometag>..."您只会获得在第一次通过循环 ( "<sometag>") 时创建的元素的 HTML 表示形式,而不是序列( )。除非......你甚至会得到那个,因为html()创建元素的表示孩子-还等什么你真的要与落得是""...

This was all just a big disappointment: you started off working with the set (Step #1), then tried to operate on the DOM (Step #3), and finished up by trying to pull data from oneDOM element (that didn't exist) (and wouldn't have had any data if it did) (Step #4).

这只是一个很大的失望:您开始使用集合(第 1 步),然后尝试对 DOM 进行操作(第 3 步),最后尝试从一个DOM 元素(没有” t 存在)(如果有,就不会有任何数据)(第 4 步)。

The solution you finally came up withisn't terrible - you're essentially opting to add oneroot element to the set starting out, and operate entirely on this DOM fragment until you're done adding new elements and are ready to operate on them. You've omitted it from your revised example, but html()would work too, since it would simply dump the contents of your root element.

您最终想出的解决方案并不糟糕——您实际上是选择在开始时向集合中添加一个根元素,然后完全对这个 DOM 片段进行操作,直到您添加完新元素并准备好对它们进行操作. 您在修改后的示例中省略了它,但html()也可以使用,因为它只会转储根元素的内容。

But just to be complete, I'll give you a final example that works on the set, starting with an empty jQuery object:

但为了完整起见,我将给出一个适用于set的最后一个示例,从一个空的 jQuery 对象开始:

var $new = $();
$.each( [1, 2, 3, 4], function(i, v)
{
  $new = $new.add("<div>");
});

alert($new.length == 4); // true

// alerts: <div></div><div></div><div></div><div></div>
alert($("<div>").append($new).html()); 

回答by Justin Geeslin

Document Fragments are perfect for this; creates an empty object ready for appending. :)

文档片段非常适合于此;创建一个准备追加的空对象。:)

$(document.createDocumentFragment())

回答by Lightness Races in Orbit

Your object $newis an empty selector, so appendhas no sets to append to.

您的对象$new是一个空选择器,因此append没有要附加的集合。

addis required to add a DOM node, and then you append to those DOM nodes. Don't think you can avoid starting with an .add.

add需要添加一个 DOM 节点,然后您附加到这些 DOM 节点。不要认为您可以避免以.add.

回答by Tom

i testet the above solution but it did not work for me, it always stayed as empty jQuery object...

我测试了上述解决方案,但它对我不起作用,它始终保持为空的 jQuery 对象...

if anybody interested, here is my solution:

如果有人感兴趣,这是我的解决方案:

var jQueryElements = [],
    $new;

$.each( [1, 2, 3, 4], function(i, v){
  jQueryElements = jQueryElements.push($('<div>').get(0));
});

$new = $(jQueryElements);

回答by Tom

if you don't want to end up with an ugly tag:

如果你不想得到一个丑陋的标签:

if(!$new){
$new.append("</sometag>");
} else {
var $new = $("</sometag>");