jQuery append() - 返回附加的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2159368/
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
jQuery append() - return appended elements
提问by psychotik
I'm using jQuery.append()to add some elements dynamically. Is there any way to get a jQuery collection or array of these newly inserted elements?
我正在使用jQuery.append()动态添加一些元素。有没有办法获得这些新插入元素的 jQuery 集合或数组?
So I want to do this:
所以我想这样做:
$("#myDiv").append(newHtml);
var newElementsAppended = // answer to the question I'm asking
newElementsAppended.effects("highlight", {}, 2000);
回答by SLaks
There's a simpler way to do this:
有一种更简单的方法可以做到这一点:
$(newHtml).appendTo('#myDiv').effects(...);
This turns things around by first creating newHtml
with jQuery(html [, ownerDocument ])
, and then using appendTo(target)
(note the "To
" bit) to add that it to the end of #mydiv
.
这通过首先创建newHtml
with jQuery(html [, ownerDocument ])
,然后使用appendTo(target)
(注意“ To
”位)将其添加到#mydiv
.
Because you now startwith $(newHtml)
the end result of appendTo('#myDiv')
is that new bit of html, and the .effects(...)
call will be on that newbit of html too.
因为你现在开始使用$(newHtml)
的最终结果appendTo('#myDiv')
是HTML的新位,而.effects(...)
通话将是对新的HTML有点太。
回答by karim79
// 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);
回答by Thiago Belem
var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);
回答by AgelessEssence
A little reminder, when elements are added dynamically, functions like append()
, appendTo()
, prepend()
or prependTo()
return a jQuery object, not the HTML DOM element.
一个小的提醒,当元件被动态添加,功能,如append()
,appendTo()
,prepend()
或prependTo()
返回一个jQuery对象,而不是HTML DOM元素。
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]"
回答by aff
I think you could do something like this:
我认为你可以做这样的事情:
var $child = $("#parentId").append("<div></div>").children("div:last-child");
The parent #parentId is returned from the append, so add a jquery children query to it to get the last div child inserted.
父 #parentId 是从追加返回的,因此向其添加一个 jquery 子查询以插入最后一个 div 子。
$child is then the jquery wrapped child div that was added.
$child 是添加的 jquery 包装的子 div。