jQuery附加DOM [英] jQuery append DOM
问题描述
jQuery.append()的所有示例似乎都占用一个html字符串并将其附加到容器中。我有一个略有不同的用例。我的服务器返回一个包含要显示的HTML文本的XML,如:
All the examples of jQuery.append() seem to take an html string and append it to a container. I have a slightly different use case. My server returns me an XML that contains HTML text to be displayed, something like:
<event source="foo">
<contents>
<h1>This is an event</h1>
This is the body of the event
</contents>
</event>
我有一个div需要显示这个内容。
I have a div where this content needs to be displayed.
我的JS目前正在执行以下操作:
My JS currently does the following:
-
在$ .ajax中将XML数据加载到jQuery中()成功处理程序:
Loads up the XML data into jQuery in the $.ajax() success handler:
var jData = $(data);
var jData = $( data );
查找内容标签并尝试将其子项添加到应该显示事件的div中:
Find the contents tag and tries to add its children to the div that is supposed to display the event:
var contents = jData.find( "contents" );
if( contents != null )
{
$( contents ).children().each( function( index, value )
{
$( "#eventDiv" ).append( $( value ) );
});
}
通过未捕获的错误调用失败:Chrome上的WRONG_DOCUMENT_ERR:DOM异常4 。调试器显示的值为DOM 元素对象, $(value)为包含元素的对象 >。
The append() call fails with Uncaught Error: WRONG_DOCUMENT_ERR: DOM Exception 4 on Chrome. The debugger shows value to be a DOM Element object and $( value ) to be an Object that contains the Element.
任何帮助将不胜感激。
谢谢。
-Raj
Thanks. -Raj
推荐答案
您不能将属于一个DOM树的节点附加到另一个文档。
You can't append nodes that belong to one DOM tree to another document.
尝试克隆他们:
$("#eventDiv").append( jData.find("contents").children().clone() );
或者只是使用他们的文本表示来重新创建它们:
or simply use their textual representation to have them re-created:
$("#eventDiv").append( jData.find("contents").html() );
这篇关于jQuery附加DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!