Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript SyntaxError:';[对象HTMLDocument]';在firefox中不是有效的选择器_Javascript_Google Chrome_Firefox - Fatal编程技术网

Javascript SyntaxError:';[对象HTMLDocument]';在firefox中不是有效的选择器

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的检查控制台中 弹出一个窗口,显

加载本地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的检查控制台中
弹出一个窗口,显示
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);
});