窗口对象始终可以使用html元素的ID吗? [英] Are IDs for an html element always available from the window object?

查看:105
本文介绍了窗口对象始终可以使用html元素的ID吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到以下几点:

 < 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆