jQuery(htmlString) versus jQuery(selectorString)

本文详细介绍了在jQuery中处理HTML字符串与选择器的注意事项,包括从1.9版本开始的改变,如何使用jQuery.parseHTML()进行正确解析,以及迁移插件的使用方法来适应不同需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值