大猫の意淫筆記
20
Feb

getElementById在IE下混淆name与id

About the author

Roger Johansson is a Swedish web professional specialising in web standards, accessibility, and usability.

原文点我 因为对我有用所以弄了过来,以下为大猫同学的不负责任翻译

 

贼.悅汗孙同学遇到了个问题,急得头皮屑直掉,后来买了瓶海飞丝,头屑去无踪...他觉得有必要强调一下这个头屑的问题

这个问题是:
当你在用getElementById去获取对应id的元素属性的时候,WIN下的IE(或某些版本的Opera)会不负责任的获取与id相同值的name对应的元素.

虽然不大可能你用同一个值命名不同元素的id和name,但一旦产生错误,会让你欲仙欲死

下面是实例:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="description" content="A brief description of the content on this page.">
<title>The name and id attributes in IE</title>
</head>
<body>
<div id="description">
<p>A description of something.</p>
</div>
</body>
</html>

OK,现在意淫一下你想要用JavaScript去非礼一下div#description.

简单的来说,比如说你想要在页面加载的时候把div#description的display属性设置为none:

function hideIt() {
var obj = document.getElementById('description');
obj.style.display = 'none';
}
window.onload = hideIt;

在IE里非礼一番后姑娘却一点反应都没有,原来是因为在IE里getElementById去找位于div元素之前name为description的meta元素去了

避免头皮屑你可以有两条路可以走

1.保证没有不同的元素身上有相同值得name和id

2.用一段script搞定>overriding IE’s native getElementById method

如果你已经意识到这问题,当我没说,如果还没,我希望你会很high.

假装异步加载ing

订阅大猫的RSS feed,不错过一部AV~ 分享到QQ空间

» You can leave a comment, or trackback from your own site.

大战 9 回合 to “getElementById在IE下混淆name与id”

  1. BigCat says:

    老大云:要美人不要江山.偶这就干活...
    话说整天发嗲会惹人厌...
    更何况...偶得假装是个高手...
    挖哈哈

    Reply

    胡戈戈:

    还有人这么翻译的

    Reply

  2. Kola says:

    第二次看到这个问题。。

    Reply

  3. BigCat says:

    自己去相应帖子根据规则留言

    Reply

  4. yacca says:

    连技术贴都咸湿 有你的 大猫

    Reply

  5. stranger says:

    ...........

    Your comment message must contain at least one chinese word!

    无语..........

    Reply

    BigCat:

    由于空间垃圾,不能用akismet...so...不好意思

    Reply

  6. EdenPlay says:

    大猫本来就是一个湿(诗)人哪!

    Reply

    BigCat:

    只是不知道为啥湿前面要加一个咸字...偶是南方人,没接触过咸湿这个词儿..

    Reply

Leave a Reply

:!: :roll: :o :lol: :P :( 8O :x :oops: :) :?: :idea: :evil: ;) :twisted: XHTML<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>