我不小心在JavaScript中键入了以下代码,它成功了:
my_element.addEventListener("click", function() {
alert("Hello world");
})
#my_element {
background: lightblue;
width: 100px;
height: 100px;
position: absolute;
top: 50px;
left: 50px;
}
<div id="my_element">hello there</div>
我没有得到元素使用:
var element = document.getElementById("my_element");
我只是简单地引用了这样的元素,它成功了!?!
my_element.addEventListener("click", function() {
alert("Hello world");
})
这适用于Firefox和Chrome。我还没有在其他浏览器中进行过测试。这是众所周知的吗?浏览器是否完全支持此功能?
我总是返回对HTML元素的引用。我感到震惊的是,我可以简单地键入元素的ID,就好像它是一个全局对象一样!
是的,它得到了普遍支持,甚至现在也在HTML5规范中。为每个具有id
的元素(以及许多其他具有name
s的元素(创建自动全局变量。
我从不依赖它,全局命名空间中有太多其他东西。但是的,这是定义的行为。
在下面的一条评论中,你问发生冲突时会发生什么。在我对另一个问题的回答中有更多内容,但这是有顺序的。自动DOM全局变量以几种不同的方式被声明的全局变量遮蔽。这里有一个例子:
// `example1` is a DOM automatic global
console.log(typeof example1); // object
console.log("example1" in this); // true
console.log(Object.prototype.hasOwnProperty.call(this, "example1")); // false
// We have both a DOM element with `example2` as its ID and also a
// `var`-declared global; the latter takes precedence
var example2;
console.log(typeof example2); // undefined
console.log("example2" in this); // true
console.log(Object.prototype.hasOwnProperty.call(this, "example2")); // true
// We have a DOM element with `example3` as its ID, a global object property
// with that name, and also a `let`-declared global variable; the latter wins
this.example3 = 42;
let example3;
console.log(typeof example3); // undefined
console.log("example3" in this); // true
console.log(Object.prototype.hasOwnProperty.call(this, "example3")); // true
.as-console-wrapper {
max-height: 100% !important;
}
<div id="example1"></div>
<div id="example2"></div>
<div id="example3"></div>
在您询问的进一步评论中:
与现有全球成员发生冲突的情况如何?例如,如果我将我的元素命名为";窗口";或";文件";?我的元素会以现有全局对象成员为先例吗?
No,window
和document
以及其他都是Window对象的自己的属性,但自动DOM全局变量在其原型上(在兼容的浏览器上;而不是IE11或IIRC Legacy Edge上(。所以它自己的财产赢了。要获得自动DOM全局,您必须访问window
的原型:
// `window` here is still the global object
console.log(window === this); // true
var someVariableName;
console.log("someVariableName" in window); // true
// The automatic DOM global "window" is on its prototype:
console.log(Object.getPrototypeOf(window).window.tagName); // "DIV"
<div id="window"></div>
当然,none是您想要依赖的行为。如果您想要通过其id
访问DOM元素,请使用getElementById
(或querySelector
或类似的(。