jQuery(htmlString) versus jQuery(selectorString)
Prior to 1.9, a string would be considered to be an HTML string if it had HTML tags anywhere within the string. This has the potential to cause inadvertent execution of code and reject valid selector strings. As of 1.9, a string
is only considered to be HTML if it starts with a less-than ("<
") character. The Migrate plugin can be used to restore the pre-1.9 behavior.
If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to
jQuery.parseHTML()
which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example:
$($.parseHTML(htmlString))
. This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as
$("<p>Testing</p>").appendTo("body")
are unaffected by this change.
Bottom line: HTML strings passed to jQuery()
that start with something other than a less-than character will be interpreted as a selector. Since the string usually cannot be interpreted as a selector, the most likely
result will be an "invalid selector syntax" error thrown by the Sizzle selector engine. Use
jQuery.parseHTML()
to parse arbitrary HTML.
When the jQuery Migrate plugin is used, it will use the old rules for determining if the string passed to
$()
"looks like HTML".
在1.9之前,字符串中如果含有html标签则被认为是一段HTML代码。这可能导致不够严谨的字符串选择器被误认为是HTML代码而报错。
1.9版本开始,只有以<开始的字符串才被认为是HTML代码。迁移插件可以用来修复1.9之前版本造成的问题。
如果想让以HTML标签开始字符串被识别为HTML代码,使用jQuery.parseHTML()
。 它将返回DOM节点的数组,并创建对应的jquery对象。比如$($.parseHTML(htmlString))这样使用。之前的使用方式如
$("<p>Testing</p>").appendTo("body")不受影响,可以仍然继续这样使用。
传递以非<开始的字符串给jquery时,该字符串将被认为是选择器。如果传入html被认为是选择器将报错为invalid selector syntax。
此时你可以考虑使用
jQuery.parseHTML()
将其转为HTML。