Javascript SyntaxError:';[对象HTMLDocument]';在firefox中不是有效的选择器
加载本地js库并运行警报命令Javascript SyntaxError:';[对象HTMLDocument]';在firefox中不是有效的选择器,javascript,google-chrome,firefox,Javascript,Google Chrome,Firefox,加载本地js库并运行警报命令 var jq = document.createElement('script'); jq.src = "http://127.0.0.1/js/jquery-3.3.1.min.js"; document.getElementsByTagName('head')[0].appendChild(jq); $(document).ready(function(){ alert("hello world"); }); 1.在chrome的检查控制台中 弹出一个窗口,显
var jq = document.createElement('script');
jq.src = "http://127.0.0.1/js/jquery-3.3.1.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
$(document).ready(function(){
alert("hello world");
});
1.在chrome的检查控制台中弹出一个窗口,显示
hellow world
,没问题
2.在firefox的控制台中。它遇到如下错误:
SyntaxError: '[object HTMLDocument]' is not a valid selector
为什么代码段不能在firefox的控制台中运行?在将这些命令输入控制台时,
$
不是jQuery,而是浏览器提供的一个帮助函数,非常类似于document.querySelector
。有关某些浏览器上可用的内置帮助器函数,请参见
您可以看到Firefox的$
的源代码:
即使$
是jQuery,行
$(document).ready(function(){
还没有提到jQuery,因为您只是插入了脚本——它还没有被下载和解析。因此,它仍然会引用querySelector
别名,并且
document.querySelector(document)
没有任何意义
最好的解决方案是在插入的脚本中附加一个load
处理程序,以便在加载jQuery后可以运行函数。例如:
const jq = document.createElement('script');
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
document.head.appendChild(jq);
jq.addEventListener('load', () => {
console.log("hello world");
console.log($ === jQuery);
});
一旦jQuery加载,它将确保
窗口。$
现在指向jQuery
而不是querySelector
别名;稍后,上面的代码片段将记录true
。开发工具提供了一个网络选项卡。请确认:资源是否http://127.0.0.1/js/jquery-3.3.1.min.js
找到(例如HTTP 200响应)?如果没有,请求的实际URL是什么$
在您的情况下不是jQuery,而是控制台中可用的document.querySelector
别名。document.getElementsByTagName('head')[0]
可以替换为document.head
。
const jq = document.createElement('script');
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js";
document.head.appendChild(jq);
jq.addEventListener('load', () => {
console.log("hello world");
console.log($ === jQuery);
});