html元素id作为javascript变量 [英] html element id as javascript variable

查看:98
本文介绍了html元素id作为javascript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

<html>
<head></head>
<body>
<div id='test' class='blah'>
  <a href='http://somesite.com/' id='someLink'>click!</a>
</div>
</body>
</html>

所以我刚刚发现,这创建一个名为 someLink ,我可以通过 someLink.href 获取href属性的值。我在最新的Chrome,FF和IE测试了这个,它的工作原理。

So I just recently discovered that this creates a javascript object called someLink and I can for instance get the value of the href attribute with someLink.href. I tested this in the latest Chrome, FF and IE and it works.

首先,这个功能已经有多久了?我想象可能有一段时间,因为我已经知道多年来,页面上的HTML元素的ID必须是唯一的,如果你有多个元素共享相同的ID,最后一个元素将覆盖以前的一个,使用getElementById()将返回最后一个。但是我从来没有真正了解为什么,但现在看来,它是一个这是创建一个对象的观点,这是有道理的。所以,只要能够直接使用id-name-as-javascript对象访问它,这是多久了? IE6时代?早些时候?

First off, how long has this "feature" been around? I imagine probably a while, because I have known for years that IDs for html elements on a page must be unique, and if you do have more than one element sharing the same ID, the last one overwrites the previous one(s), and using for instance getElementById() will return the last one. But I never really understood why, but now, looking at it as a "this is creating an object" perspective, it makes sense. So, as far as being able to directly access it with the id-name-as-javascript object...how long has that been around? IE6 era? Earlier?

第二...我猜这更像是一个讨论点而不是问题,但是... IMO似乎不是一个非常好的功能拥有...不是有一个DOM和包装器功能的整体,像 getElementById(),给一些组织,更重要的是减少命名空间问题?我不觉得我应该担心页面上的随机html元素会覆盖我的javascript变量(最近发生的事情,这就是为什么我发现了这个功能)。有没有人知道为什么这是这样的,它背后的逻辑是什么?

2nd...I guess this is more of a discussion point than question, but... IMO this doesn't seem like a very good "feature" to have... Isn't the whole point of having a DOM and wrapper functions like getElementById(), to give some organization and more importantly, cut down on namespace issues? I don't feel I should have to be worried about random html elements on a page overwriting my javascript variables (something that has recently happened, which is why I discovered this "feature"). Does anybody know why this is as it is, what's the logic behind it?

推荐答案


首先,这个功能已经有多久了?

First off, how long has this "feature" been around?

如果我记得正确的话,这是一个微软在IE 4上出现的微软。

It is a Microsoft-ism that cropped up around IE 4 if I remember correctly.

其他一些浏览器已经添加了对它的支持,以便与依赖于它的严重编写的代码兼容。有些可能只支持怪癖模式

Some other browsers have added support for it in an effort to be compatible with badly written code that depends on it. Some may only support it in quirks mode.


这似乎不是一个非常好的功能,具有

this doesn't seem like a very good "feature" to have

正确。不要使用它:)

这篇关于html元素id作为javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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