jQuery append()-返回附加元素


Answers:


263

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

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

这原来周围的事物,首先创建newHtmljQuery(html [, ownerDocument ]),然后使用appendTo(target)(注意“ To”位)给它添加到年底#mydiv

因为你现在开始使用$(newHtml)的最终结果appendTo('#myDiv')是HTML的新位,而.effects(...)通话将是对的HTML有点太。


2
使用jQuery UI的版本1.9.2我越来越effects不是一个功能......但effect就是
菲利普中号

我要补充一点,还有另一个签名:appendTo(target,context)。例如,对于任何jQuery选择器,它仅允许在特定上下文内搜索target,但。如果您编写插件或库,这将非常有用。
Pierpaolo Cira

1
这是否会引发错误newHtml不是有效的HTML或有效jQuery选择:$('/ This is Not HTML /').appendTo('#myDiv')结果Uncaught Error: Syntax error, unrecognized expression,而$('#myDiv').append('/ This is Not HTML /')通过附加文本到目标元素正常工作。
Thomas CG de Vilhena

40
// 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
当我稍后尝试将事件绑定到附加元素时,这对我不起作用。我使用了var appendedTarget = $(newHtml).appendTo(element)。然后,我可以使用$(appendTarget).bind('keydown',someFunc)进行绑定-Zac
Imboden

我认为$elements.effect("highlight", {}, 2000);不是effects
为什么

2
这是行不通的,因为$ elements变量在附加,更改后不再可用。
Alex V

@AlexV这似乎有效,请参见jsbin.com/xivedohofi/1/edit?html,js,output上的实时演示,还可以看到与类似问题stackoverflow.com/questions/1443233/…
Adrien Be

2
看来他们已在较新版本的jQuery中修复了此问题。
Alex V


10

一个小的提醒,当元件被动态添加,功能,如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]"

19
从append()返回的元素是容器,而不是新元素。
Tomas

0

我认为您可以执行以下操作:

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

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.