javascript - 给innerHTML赋值会不会异常?

标签 javascript dom

我通读了https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML ,它声称 SyntaxError可能会发生。

dom = document.createElement('div')
// output: <div></div>
dom.innerHTML = '[try.various.strings.here]'
// output: "[try.various.strings.here]"
dom
// check final DOM

我尝试用 <div> 替换测试字符串(部分),<div (坏了)和<div></p> (无与伦比)。我从来没有遇到过异常(exception)。我想知道是否需要为其添加预检查或保护 ( try..catch )。

最佳答案

长话短说

规范说如果浏览器需要它可以,但我不认为任何主流浏览器都这样做HTML(好吧,我不会对 IE9-IE11 和实际上是某些元素类型)。 (而它们对 XML 。)来自 HTML 5.2 specification 中 HTML 解析器的定义。 :

This specification defines the parsing rules for HTML documents, whether they are syntactically correct or not. Certain points in the parsing algorithm are said to be parse errors. The error handling for parse errors is well-defined (that’s the processing rules described throughout this specification), but user agents, while parsing an HTML document, may abort the parser at the first parse error that they encounter for which they do not wish to apply the rules described in this specification.

(我的重点)

详情

DOM Parsing and Serialization spec定义 innerHTML,并说:

On setting, these steps must be run:

  1. Let fragment be the result of invoking the fragment parsing algorithm with the new value as markup, and the context object as the context element.
  2. If the context object is a template element, then let context object be the template's template contents (a DocumentFragment).
  3. Replace all with fragment within the context object.

如果我们点击片段解析算法链接,我们可以:

The following steps form the fragment parsing algorithm, whose arguments are a markup string and a context element:

  1. If the context element's node document is an HTML document: let algorithm be the HTML fragment parsing algorithm.
    If the context element's node document is an XML document: let algorithm be the XML fragment parsing algorithm.
  2. Let new children be the result of invoking algorithm with markup as the input, and context element as the context element.
  3. Let fragment be a new DocumentFragment whose node document is context element's node document.
  4. Append each Node in new children to fragment (in tree order).
  5. Return the value of fragment.

如果我们遵循上面的HTML 解析算法 链接,我们将获得创建和使用 HTML 解析器的步骤。如果我们点击指向 HTML 解析器定义的链接,我们将获得上面 TL;DR 中的第一个链接和上面引用的文本。

关于javascript - 给innerHTML赋值会不会异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50922305/

相关文章:

javascript - 如何使用 KnockoutJS 在 foreach 循环中指定不同的点击绑定(bind)

javascript - 在 Javascript 中,如何确定我当前的浏览器是计算机上的 Firefox 还是其他浏览器?

javascript - 为什么getComputedStyle不返回显示:none for an element hidden by a parent?

javascript - 如何根据 DOM 级别猜测浏览器兼容性?

javascript - Meteor js,body.helper函数getElementsByTagName

javascript - 无法使用 Geolocations API 在 JS Codepen 中的函数之间传递 var

javascript - 如何在 JavaScript 中检测 iOS 模拟器

javascript - 如何制作像 Facebook 的 "Chat/Event Ticker"那样可调整大小、可滚动的侧边栏?

java - 如何通过 DOM Parser/Java 交换两个 XML 元素

javascript - 下载html时如何获取文本值而不是[object NodeList]?