[英]SyntaxError: '[object HTMLDocument]' is not a valid selector in firefox
To load my local js lib and run an alert command. 加载我的本地js lib并运行alert命令。
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.In chrome's inspect--console 1.在chrome的检查 - 控制台
Pop up a window with hellow world
,no problem. 弹出一个拥有hellow world
的窗口,没问题。
2.in firefox's console. 2.在firefox的控制台。
It run into an error as below: 它遇到如下错误:
SyntaxError: '[object HTMLDocument]' is not a valid selector
Why the code snippet can't run in firefox's console? 为什么代码片段无法在firefox的控制台中运行?
At the time that those commands are entered into the console, $
is not jQuery - rather, it is a helper function provided by the browser that is very similar to document.querySelector
. 在将这些命令输入控制台时, $
不是jQuery - 相反,它是浏览器提供的辅助函数 ,与document.querySelector
非常相似。 See docs on the built-in helper functions available on some browsers. 见文档对某些浏览器提供的内置辅助功能。
You can see the source for Firefox's $
here : 您可以在此处查看Firefox $
的来源:
WebConsoleCommands._registerOriginal("$", function(owner, selector) {
try {
return owner.window.document.querySelector(selector);
} catch (err) {
// Throw an error like `err` but that belongs to `owner.window`.
throw new owner.window.DOMException(err.message, err.name);
}
});
Even if $
were jQuery, the line 即使$
是 jQuery,也行
$(document).ready(function(){
wouldn't refer to jQuery yet, because you only just inserted the script - it hasn't necessarily been downloaded and parsed yet. 不会引用jQuery,因为你只是插入了脚本 - 它尚未被下载和解析。 So, it'll still refer to the querySelector
alias, and 所以,它仍然会引用querySelector
别名,和
document.querySelector(document)
doesn't make any sense. 没有任何意义。
The best solution would be to attach a load
handler to the inserted script, so that you can run a function once jQuery is loaded. 最好的解决方案是将一个load
处理程序附加到插入的脚本,以便在加载jQuery后运行一个函数。 For example: 例如:
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);
});
Once jQuery loads, it will ensure that window.$
now points to jQuery
rather than the querySelector
alias; 一旦jQuery加载,它将确保window.$
now指向jQuery
而不是querySelector
别名; the above snippet will log true
after a moment. 上面的代码片段将记录true
片刻后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.