简体   繁体   English

使用jQuery附加为同级而不是子元素

[英]Using jQuery to append as sibling rather than child element

I can't seem to find the functionality that I'm looking for. 我似乎找不到所需的功能。 I need to append some DOM elements, as siblings, to a disconnected node. 我需要将一些DOM元素作为兄弟添加到断开连接的节点上。

Seems pretty straight forward, and according to the jQuery documentation I should be able to do this with either .after() or .add(), but neither word: 似乎很简单,根据jQuery文档,我应该可以使用.after()或.add()做到这一点,但是两个字都不能:

var $set = $('<div class="parent"></div>');
    $set.add('<div class="child"></div>');
    $set.add('<div class="child"></div>');
    $set.add('<div class="child"></div>');
$('body').append($set);

http://jsfiddle.net/kh9Uj/17/ and http://jsfiddle.net/kh9Uj/19/ http://jsfiddle.net/kh9Uj/17/http://jsfiddle.net/kh9Uj/19/

It works if I chain them using .add(): 如果我使用.add()将它们链接起来,它将起作用:

$('<div class="parent"></div>')
    .add('<div class="child"></div>')
    .add('<div class="child"></div>')
    .add('<div class="child"></div>')
.appendTo('body');

http://jsfiddle.net/kh9Uj/23/ http://jsfiddle.net/kh9Uj/23/

But not with .after(), and in my application I don't have the option on chaining them. 但是没有.after(),在我的应用程序中,我没有链接它们的选项。 How can I do this? 我怎样才能做到这一点?

Edited to fix class / id issue. 编辑以解决类/ id问题。

set does not update the variable 设置不会更新变量

var $set = $('<div id="parent">0</div>');
$set = $set.add('<div id="child1">1</div>');
$set = $set.add('<div id="child2">2</div>');
$set = $set.add('<div id="child3">3</div>');
$('body').append($set);

Chaining works because you are adding them to the same object. 链接之所以起作用,是因为您将它们添加到了同一对象中。

var $set = $('<div id="parent">0</div>')          //first element
               .add('<div id="child1">1</div>')   //second element in object
               .add('<div id="child2">2</div>')   //third
               .add('<div id="child3">3</div>');  //fourth
$('body').append($set);

BUT add is not adding it to parent. 但是添加不会将其添加到父项。 It is adding it as " siblings " when you append it. 当您添加它时,它将作为“ 兄弟姐妹 ”添加。

<parent />
<child1 />
<child2 />
<child3 />

If you want the "child" elements to be children of "parent" you need to use append. 如果希望“子级”元素是“父级”的子级,则需要使用append。

var $set = $('<div id="parent">0</div>');
$set.append('<div id="child1">1</div>');
$set.append('<div id="child2">2</div>');
$set.append('<div id="child3">3</div>');
$('body').append($set);

which results in 导致

<parent>
    <child1 />
    <child2 />
    <child3 />
</parent>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM