检查HTML代码段是否对Javascript有效

编程入门 行业动态 更新时间:2024-10-28 04:21:13
本文介绍了检查HTML代码段是否对Javascript有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要一个可靠的Javascript库/函数来检查HTML代码段是否有效,我可以从我的代码中调用。例如,它应该检查打开的标记和引号是否关闭,嵌套是否正确等。

我不希望验证失败,因为某些不是100 %标准(但无论如何会起作用)。

解决方案

更新:此答案有限 - 请参阅在下面的编辑。

扩展@ kolink的答案,我使用:

var checkHTML = function(html){ var doc = document.createElement('div'); doc.innerHTML = html; return(doc.innerHTML === html); }

即,我们用HTML创建一个临时div。为了做到这一点,浏览器将创建一个基于HTML字符串的DOM树,这可能涉及到关闭标签等。

比较div的HTML内容和原始HTML将告诉我们浏览器是否需要更改任何内容。

checkHTML('< a>地狱< b> o< / b> ;')

返回false。

checkHTML('< a> hell< b> o< / b>< / a>')

返回true。

编辑:@Quentin注释如下,过分由于各种原因,浏览器通常会修正省略的结束标记,即使结束标记对于该标记是可选的。例如:

< p>一个段落< p>第二段落 $ b

...被认为是有效的(因为Ps允许省略结束标记),但 checkHTML 将返回false。浏览器还会标记标记案例,并改变空白区域。决定使用这种方法时应该意识到这些限制。

I need a reliable Javascript library / function to check if a HTML snippet is valid that I can call from my code. For example, it should check that opened tags and quotation marks are closed, nesting is correct, etc.

I don't want the validation to fail because something is not 100% standard (but would work anyways).

解决方案

Update: this answer is limited - please see the edit below.

Expanding on @kolink's answer, I use:

var checkHTML = function(html) { var doc = document.createElement('div'); doc.innerHTML = html; return ( doc.innerHTML === html ); }

I.e., we create a temporary div with the HTML. In order to do this, the browser will create a DOM tree based on the HTML string, which may involve closing tags etc.

Comparing the div's HTML contents with the original HTML will tell us if the browser needed to change anything.

checkHTML('<a>hell<b>o</b>')

Returns false.

checkHTML('<a>hell<b>o</b></a>')

Returns true.

Edit: As @Quentin notes below, this is excessively strict for a variety of reasons: browsers will often fix omitted closing tags, even if closing tags are optional for that tag. Eg:

<p>one para <p>second para

...is considered valid (since Ps are allowed to omit closing tags) but checkHTML will return false. Browsers will also normalise tag cases, and alter white space. You should be aware of these limits when deciding to use this approach.

更多推荐

检查HTML代码段是否对Javascript有效

本文发布于:2023-07-11 17:11:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1094797.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   HTML   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!