窗口对象始终可以使用html元素的ID吗? [英] Are IDs for an html element always available from the window object?
问题描述
我注意到以下几点:
< div id ='myDiv'> ...< / div>
< script>
myDiv.style.color ='red'; //我可以访问该对象。
< script>
在实现这个之前,我总是使用以下内容:
var x = document.getElementById('myDiv');
x.style.color ='red';
我很困惑。第二种方法有什么意义?第一种方法是否始终有效?
HTML元素的ID总是可以从窗口对象中获得?
没有。出于兼容性的原因,某些其他浏览器采用了非标准的Microsoft-ism。它很容易出现命名空间冲突,并且不能完全跨浏览器兼容:不这样做。
第二种方法的意义何在? ?
它是标准的,支持良好的跨浏览器(也是跨语言)。
I noticed the following:
<div id='myDiv'>...</div>
<script>
myDiv.style.color = 'red'; // I can access the object.
<script>
Before realizing this, I was always using the following:
var x = document.getElementById('myDiv');
x.style.color = 'red';
I am confused. What's the point of the second approach? Does the first approach always work?
Are IDs for an html element always available from the window object?
No. It is a non-standard Microsoft-ism that some other browsers have adopted for compatibility reasons. It is prone to namespace collisions, and not completely cross-browser compatible: don't do it.
What's the point of the second approach?
It is standard, well-supported cross-browser (and also cross-language).
这篇关于窗口对象始终可以使用html元素的ID吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!