jquery可以操纵用DOM创建的临时文档吗? [英] Can jquery manipulate a temporary document created with DOM?

查看:132
本文介绍了jquery可以操纵用DOM创建的临时文档吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的是使用jQuery通过传递一个大的html字符串来处理使用DOM创建的文档。请考虑以下示例:

The thing that I want to achieve is to manipulate a document created with DOM using jquery by passing a big html string. Consider the following example:

var doctype = document.implementation.createDocumentType( 'html', '', '');
var dom = document.implementation.createDocument('', 'html', doctype);
dom.documentElement.innerHTML = '<head><head><title>A title</title></head><body><div id="test">This is another div</div></body>'; 

这将在dom中创建一个新文档,并提供内容。现在我想使用jquery来附加我们现在的div里面的div。

This will create a new document in dom, with the content provided. Now I want to use jquery to append let's say a div inside the existing div.

$('#test',dom).append('<div> A second div</div>');
console.log(dom);

当我在控制台中打印结果似乎'dom'的innerHTML没有改变。从jquery的API文档中, http://api.jquery.com/jQuery/ 更具体的 jQuery(selector [,context])函数应该允许这个。

When I print the result in the console it seems that the innerHTML of the 'dom' has not changed. From the API documentation of jquery,http://api.jquery.com/jQuery/ more specific "jQuery( selector [, context ] )" function should allow this.

由于有人可能会争辩使用控制台进行调试,所以我提供了另一部分代码不工作:

Since someone may argue about using the console to debug, I am providing below another part of code that does not work:

$('body').append($('#test',dom));

使用chrome和firefox进行测试,并且不适用于最新的jquery库。

Tested in chrome and firefox and it does not work with the latest jquery library.

推荐答案

通过更改构造函数并使用以下行

By changing the constructors and using the line below

var dom = document.implementation.createHTMLDocument("Test");

而不是最初引入的两行

var doctype = document.implementation.createDocumentType( 'html', '', '');
var dom = document.implementation.createDocument('', 'html', doctype);

一切正常,即使直接设置innerHTML

everything works fine, even when setting the innerHTML directly!

这篇关于jquery可以操纵用DOM创建的临时文档吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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