JavaScript getElementById('id')==querySelector('#id') //true 为什么相等.

2019-05-15 16:27:08 +08:00
 TomVista

按道理讲 getElementById('id')获得一个 HTMLElement 对象,querySelector('#id')获得一个 Element 对象.

Element<=HTMLElement,它俩是继承关系.

我有一点点明白,但又说不上来...

另外 Element 没有 event 事件,但是浏览器中能通过 element 对象访问 onSomething();

1324 次点击
所在节点    问与答
7 条回复
temporary
2019-05-15 16:37:18 +08:00
返回的都是 Element 吧?
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
The Document method querySelector() returns the first Element within the document that matches the specified selector
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string
fitmewell
2019-05-15 16:43:15 +08:00
一个接口返回白马 一个接口返回马 ,白马的编号是 1 同时根据 2 个接口要求返回编号为 1 的数据 ,返回的都是白马
abc635073826
2019-05-15 16:48:13 +08:00
有请公孙龙来证:白马非马
TomVista
2019-05-15 17:03:11 +08:00
@temporary 返回的确实不一样.
@fitmewell @abc635073826 逻辑陷阱...
geelaw
2019-05-15 17:08:25 +08:00
@temporary #1 在文档更靠后的返回值部分用了不同的类型。

HTMLElement 是 Element 的子类(更准确地说是 IHtmlElement 是 IElement 的子接口),一个 HTMLElement 对象自然也是 Element 对象(一个实现了 IHtmlElement 接口的对象自然也实现了 IElement 接口)。

JavaScript 是动态类型语言,因此通过对象的引用可以访问的方法 /属性 /事件只和对象的运行时类型有关系,和“引用的静态类型”无关——打引号是因为后面这个概念在 JavaScript 里根本不存在。

换句话说,这代码大概可以这样翻译成 C++:

IUnknown *ptr;

IHtmlElement *getElementById(...)
{
return dynamic_cast<IHtmlElement *>(ptr);
}

IElement *querySelector(...)
{
return dynamic_cast<IElement *>(ptr);
}

这返回的是同一个对象,如果在 C++ 里比较,那就相当于是

dynamic_cast<IUnknown *>(getElementById(...)) == dynamic_cast<IUnknown *>(querySelector(...))

这当然是相等的。当然,这在 JavaScript 里面都是不存在的——你可以认为所有的 JavaScript 对象都是 IDispatch2。
rabbbit
2019-05-15 17:08:47 +08:00
document.querySelector('#Main') == "[object HTMLDivElement]" // true
document.getElementById('Main') == "[object HTMLDivElement]" // true
MrKou47
2019-05-16 00:30:29 +08:00
这个问题的关键不在于 js 的继承,而在于 ecma 规定的==操作符的算法。建议楼主先看规范

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/564412

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX