javascript - jQuery() 与 jQuery.parseHtml() 空格语法错误

标签 javascript jquery

我有一行 javascript 在 jQuery 中导致语法错误:

$(document).find('.Container').replaceWith($(data).find('.Content'));

代码本身如果相当无害的话,它所做的就是从 ajax 调用中获取响应数据,以一些内部内容为目标,然后用该内容替换容器 div 元素的内容。然而,当响应数据有前导空格时,它会导致 jQuery 中的语法错误。

例如,以下剥离后的响应数据就可以了:

$("<!DOCTYPE html><html><head></head><body></body></html>")

但是前面有空格的相同响应不是:

$(" <!DOCTYPE html><html><head></head><body></body></html>")

并给出以下错误信息:

Syntax error, unrecognized expression: <!DOCTYPE html><html><head></head><body></body></html>

我猜这可能与 jQuery 测试 jQuery 函数参数($() 是其别名)以区分不同重载的方式有关。

我还注意到 jQuery 函数 $.parseHTML() 似乎可以处理前导空格,因为以下代码行很好:

$.parseHTML(" <!DOCTYPE html><html><head></head><body></body></html>")

有谁知道这是否是 jQuery 的错误?或者只是 jQuery() 函数要求它不应该有前导空格的情况。

顺便说一句,jQuery 的版本是 1.9.1

更新 ************************************************ **********************************************

多亏了一位同事的提示,我发现这是一个真正的错误(尽管它最初并没有被 jQuery 团队接受为错误 - read the comments)。看起来它将/已经在 jQuery 1.10/2.0 中“修复”。

最佳答案

来自docs :

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with <tag ... >)

看来 jQuery 正在寻找 <tag在你的字符串的开头并没有找到它。然后回过头来尝试将其解析为一个选择器,这当然是无效的

关于javascript - jQuery() 与 jQuery.parseHtml() 空格语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23061718/

相关文章:

javascript - 在 Chrome 扩展的 iframe 中使用 Twitter Bootstrap JS

javascript - 在多个事件上运行函数

java - Struts Web 应用程序 : Reusable Validation Client-Side & Server-Side

javascript - 如何在 Wordpress 上延迟嵌入 YouTube 视频的 javascript?

javascript - 进行属性别名的最佳方法?

javascript - 在 ES6 javascript 中更新现有对象数组

javascript - 谷歌地图最佳实践?

javascript - 是否可以使用 JQuery 或 JavaScript 更改窗口大小?

javascript - 无法使用 AJAX localhost 请求 html 内容

javascript - 有没有更好的方法来使用 javascript 清理输入?