【发布时间】:2021-03-23 17:26:36
【问题描述】:
例子:
$(document).click(function() { blah });
// and
$('html').click(function() { blah });
【问题讨论】:
-
在上面的场景中......我认为两者都是一样的。
标签: javascript jquery
例子:
$(document).click(function() { blah });
// and
$('html').click(function() { blah });
【问题讨论】:
标签: javascript jquery
我会分几个部分回答这个问题。
在 JavaScript(不仅仅是 jQuery,而是所有 JavaScript)中,document 关键字是包含 HTMLDocument 的对象的句柄。您可能会在以下场景中使用此句柄...
// Get the current web address
alert(document.location.href);
当您将文档传递给 jQuery 时,它会将文档解析为 jQuery 对象。
当您将“html”选择器传递给 jQuery 时,它会使用此字符串来查找文档对象模型中与选择器匹配的任何元素(在所有情况下,都会有一个 html 元素)。
实际上,您不会注意到它们之间的行为差异:
$(document).click(function() { alert('blah'); });
$('html').click(function() { alert('blah'); });
$('body').click(function() { alert('blah'); });
但技术上的区别在于 document 是一个对象,而 'html' 是一个用于搜索元素的字符串。对象和任何匹配的元素都被转换为 jQuery 对象。
因为他们都将点击事件处理程序添加到页面的“可见”部分,这是用户可以实际点击的页面的唯一部分。
【讨论】:
尝试把两者的innerHTML都拿出来,结果如何?我认为(但未经测试)
document 确实是完整的文档,包括 <html> 和其中的所有元素html 引用 <html>-tag,因此您的输出中只会有 <head> 和 <body>,而不是 <html>-tag 本身但是:对于您的代码(添加点击处理程序)没有区别,因为点击文档将始终点击<html>(只要您的网站有效并且有 <html>-tag)
【讨论】:
他们选择相同的东西。唯一的区别是 jQuery 的嘶嘶声引擎如何找到它。第一种情况是 jQuery init 函数中的一种特殊情况,第二种情况使用 getElementsByTagName
【讨论】:
区别不大:
document 和 <html> 都是节点document 是 Document 的一个实例,而 <html> 是 Element 的一个实例
document 包括<!DOCTYPE...> 标签以及<html> 标签// document
console.log('-----------document inheritance chain------------')
console.log(document.__proto__.constructor.name)
console.log(document.__proto__.__proto__.constructor.name)
console.log(document.__proto__.__proto__.__proto__.constructor.name)
console.log(document.__proto__.__proto__.__proto__.__proto__.constructor.name)
console.log(document.__proto__.__proto__.__proto__.__proto__.__proto__.constructor.name)
// html element
const HTML = document.getElementsByTagName('html')[0]
console.log('-----------<html> inheritance chain------------')
console.log(HTML.__proto__.constructor.name)
console.log(HTML.__proto__.__proto__.constructor.name)
console.log(HTML.__proto__.__proto__.__proto__.constructor.name)
console.log(HTML.__proto__.__proto__.__proto__.__proto__.constructor.name)
console.log(HTML.__proto__.__proto__.__proto__.__proto__.__proto__.constructor.name)
console.log(HTML.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.constructor.name)
console.log('-----------document child-nodes------------')
console.log(document.childNodes.length);
console.log(document.childNodes[0].name);
console.log(document.childNodes[1] === HTML);
祝你好运……
【讨论】:
console.log(document.documentElement.parentNode) //输出是文档 console.log(document.documentElement.parentElement) //输出是空 --------- --------------- 在第二种情况下输出为空,因为 html 的父级是文档,它只是一个节点,而不是一个元素。
document instanceof Element 返回 false 而 document instanceof Node 返回 true。感谢分享! :)