jQuery append() - 返回附加的元素

时间:2010-01-29 01:47:06

标签: jquery

我正在使用jQuery.append()动态添加一些元素。有没有办法获得这些新插入元素的jQuery集合或数组?

所以我想这样做:

$("#myDiv").append(newHtml);
var newElementsAppended = // answer to the question I'm asking
newElementsAppended.effects("highlight", {}, 2000);

5 个答案:

答案 0 :(得分:252)

有一种更简单的方法可以做到这一点:

$(newHtml).appendTo('#myDiv').effects(...);

首先使用jQuery(html [, ownerDocument ])创建newHtml,然后使用appendTo(target)(请注意“To”位)将其添加到结尾#mydiv

因为您现在$(newHtml) 开始,appendTo('#myDiv')的最终结果是html的新位,.effects(...)调用将在新的位html。

答案 1 :(得分:39)

// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);

// append to the DOM
$("#myDiv").append($elements);

// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);

答案 2 :(得分:28)

var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);

答案 3 :(得分:10)

提醒,当动态添加元素时,append()appendTo()prepend()prependTo()等函数会返回jQuery对象,不是HTML DOM元素。

DEMO

var container=$("div.container").get(0),
    htmlA="<div class=children>A</div>",
    htmlB="<div class=children>B</div>";

// jQuery object
alert( $(container).append(htmlA) ); // outputs "[object Object]"

// HTML DOM element
alert( $(container).append(htmlB).get(0) ); // outputs "[object HTMLDivElement]"

答案 4 :(得分:0)

我认为你可以这样做:

var $child = $("#parentId").append("<div></div>").children("div:last-child");

从追加返回父#parentId,因此向其添加一个jquery children查询以获取插入的最后一个div子节点。

$ child是添加的jquery包装的子div。