用jQuery解析无效的HTML,而不添加DOM? [英] Parsing invalid HTML with jQuery, without adding to DOM?

查看:101
本文介绍了用jQuery解析无效的HTML,而不添加DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用HTML模板的jQuery插件。最终用户可能会传递一个模板,看起来像这样最简单的级别:

 < template> 
< img src =/ images / image_ {field_id} .gif>
< / template>

模板应该被注释掉,这样浏览器就不会尝试渲染任何东西,我的代码只是将注释的内部提取为文本,然后使用jQuery将其解析为元素树。然后我做具体的替换。



我记得读过jQuery只是使用DOM来解析HTML,例如当你只是做

  var x = $(html_string); 

jQuery实际上只是将其添加到DOM中以获取元素。上面的简单操作不会渲染任何东西(直到我实际上在DOM中的某个地方添加了 x ),但是此代码导致浏览器尝试加载图像目标 - 即使我没有将它添加到DOM中。这是一个简单的演示,这个效果在行动中: http: //jsfiddle.net/b5HGU/



所以基本上 - 有没有办法解决这个问题?您可以使用jQuery创建一个具有已知错误 src 标签的image元素,但是在实际将其添加到真实的DOM之前,它不会加载映像?



另一种替代方法是使用jQuery构建DOM来完成模板上的所有解析,作为之前的字符串。这当然是可行的,但实际上模板有许多不同的组件,在输出解析版本之前,使用jQuery选择器将其转换为导航树是非常方便的。否则我必须基本上写我自己的XML解析器。只是想知道在我这样做之前是否有任何简单的解决方案。

解决方案

尝试调用 $ .parseXML ,它应该将其视为原始标记而不解释任何东西。



我怀疑它需要形成良好。 p>

I'm working on a jQuery plugin that uses an HTML template. End users may pass in a template that looks at the simplest level like this:

<template>
   <img src="/images/image_{field_id}.gif">
</template>

The template is supposed to be commented out, so that the browser won't try to render anything, My code just extracts the interior of the comment as text, and then uses jQuery to parse it into an element tree. Then I do specific substitutions.

I remember reading that jQuery just uses the DOM to parse HTML, e.g. when you just do

var x = $(html_string);

jQuery is actually just adding it to the DOM to get the elements. The simple action above would not render anything (until I actually added x somewhere in the DOM), but yet this code results in the browser trying to load the image target - even if I never add it to the DOM. Here is a simple demonstration of this effect in action: http://jsfiddle.net/b5HGU/

So basically - is there any way to solve this problem? Can you create an "image" element with a known bad src tag using jQuery, but have it not load the image until you actually add it to the real DOM?

The other alternative I have is to complete all the parsing on the template, as a string, before using jQuery to construct a DOM. This is certainly doable, but in reality the template has a number of different components, and it is very convenient to use jQuery selectors to turn it into a navigable tree before outputting the parsed version. I'd have to basically write my own XML parser otherwise. Just wondering if there are any simple solutions before I do this the hard way.

解决方案

Try calling $.parseXML, which should treat it as raw markup without interpreting anything.

I suspect that it will need to be well-formed.

这篇关于用jQuery解析无效的HTML,而不添加DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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