jQuery附加DOM [英] jQuery append DOM

查看:115
本文介绍了jQuery附加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:


  1. 在$ .ajax中将XML数据加载到jQuery中()成功处理程序:

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆