在IE上,document.getElementsByName不起作用 [英] On IE document.getElementsByName won't work

查看:142
本文介绍了在IE上,document.getElementsByName不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码:

<div name="1234">
   <img src="pic.gif" height="70" width="100" onMouseOver="clear('1234')">
</div> 

并且:

function clear(element_name){
    document.getElementsByName(element_name)[0].innerHTML="";
}

它在Firefox和Opera中有效,但在IE 6.0中不起作用或IE 8.0,甚至可能不适用于较新的IE。

It does work in Firefox and Opera, but doesn't work in IE 6.0 or IE 8.0, and probably not even in newer IE's.

怎么办?

推荐答案

嗯,问题是:IE将document.getElementsByName(...)[0]理解为document.getElementById(...)。因此,如果您还要为您的元素定义一个id,方法document.getElementsByName(element_name)[0] .innerHTML =也会令人惊讶地在IE中工作!

Well, the problem is this: IE understands document.getElementsByName(...)[0] as document.getElementById(...). So if you would define also an id for your element, the method document.getElementsByName(element_name)[0].innerHTML="" will surprisingly also work in IE!

但是因为你无论如何都需要根据IE定义一个id,并且因为id必须始终以char开头,所以你必须使用:

But since you anyway need to define an id due to IE, and since an id must always start with a char first, you must use:

<div id="a234">
    <img src="pic.gif" height="70" width="100" onMouseOver="clear('a234')">
</div> 

此命令:

function clear(element_id){
    document.getElementById(element_id).innerHTML="";
}

更多,document.getElementsByName(...)[0]速度较慢在Firefox中: http://www.uize.com/tests/performance/ getElementById-vs-getElementsByName.html

Even more, document.getElementsByName(...)[0] is slower in Firefox: http://www.uize.com/tests/performance/getElementById-vs-getElementsByName.html

所以id肯定会赢得比赛。

So the id definitely wins the race.

更新:

同样重要的是,我们可以在 CSS <中使用#a234 {...}来识别每个ID / strong>文件。因此,我们可以为每个id 定义自己的样式,这使得id更加强大。

Also important is the fact, that we can adress every id by #a234{...} in a CSS file. So we can define an own style for every id, and this makes the id even more powerful.

这篇关于在IE上,document.getElementsByName不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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