从一个字符串构造一个DOM树而不加载资源(特别是图像) [英] construct a DOM tree from a string without loading resources (specifically images)

查看:85
本文介绍了从一个字符串构造一个DOM树而不加载资源(特别是图像)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我通过AJAX抓住RSS提要。在处理它们之后,我有一个html字符串,我想使用各种jQuery功能来操作。为了做到这一点,我需要一个DOM节点树。

So I am grabbing RSS feeds via AJAX. After processing them, I have a html string that I want to manipulate using various jQuery functionality. In order to do this, I need a tree of DOM nodes.

我可以将HTML字符串解析成jQuery()函数。

I可以将它添加为innerHTML到一些隐藏的节点并使用它。

我甚至尝试使用mozilla的非标准的range.createContextualFragment()。

I can parse a HTML string into the jQuery() function.
I can add it as innerHTML to some hidden node and use that.
I have even tried using mozilla's nonstandard range.createContextualFragment().

问题所有这些解决方案都是当我的HTML片段具有< img> 标签时,firefox会尽可能地获取引用的任何图片。由于这个处理是没有向用户显示的背景资料,所以我只想得到一个没有的浏览器加载其中包含的所有图像的DOM树。

The problem with all of these solutions is that when my HTML snippet has an <img> tag, firefox dutifully fetches whatever image is referenced. Since this processing is background stuff that isn't being displayed to the user, I'd like to just get a DOM tree without the browser loading all the images contained in it.

这可能与javascript?我不介意,如果它是仅限于mozilla,因为我已经在使用JavaScript 1.7功能(现在似乎只是mozilla)

Is this possible with javascript? I don't mind if it's mozilla-only, as I'm already using javascript 1.7 features (which seem to be mozilla-only for now)

推荐答案

答案是这样的:

var parser = new DOMParser();
var htmlDoc = parser.parseFromString(htmlString, "text/html");
var jdoc = $(htmlDoc);
console.log(jdoc.find('img'));

如果您注意您的Web请求,您会注意到,即使html字符串被jquery解析和包装。

If you pay attention to your web requests you'll notice that none are made even though the html string is parsed and wrapped by jquery.

这篇关于从一个字符串构造一个DOM树而不加载资源(特别是图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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