2011-09-19 63 views
0

http://jsfiddle.net/Gch83/为什么这个单行JS在Firefox中不起作用?

<input id="myRadioButton1" name="radiobutton" value="radiobutton" type="radio">1 
<input id="myRadioButton2" name="radiobutton" value="radiobutton" type="radio">2 

<input value="1 checked" onMouseOver="document.all.myRadioButton1.checked = true;" type="button"> 
<input value="2 checked" onMouseOver="document.all.myRadioButton2.checked = true;" type="button"> 

悬停在按钮改变单选按钮在Chrome,而不是Firefox浏览器。

这是为什么?

回答

2

使用

<input value="1 checked" onMouseOver="document.getElementById('myRadioButton1').checked = true;" type="button"> 

<input value="2 checked" onMouseOver="document.getElementById('myRadioButton2').checked = true;" type="button"> 

reason是因为它是由IE引入的,而不是标准DOM document.all不FF支持。

演示可以发现here

1

基本上说,使用document.all是非标准的。

事实上,这是javascript程序员应该避免的。它是Internet Explorer 4(大约在1997年!)的遗留物,并且被包括在内,因为当时有一些非常基本的DOM API尚未标准化(例如document.getElementById)。如果现代浏览器支持任何这些旧的DOM API,它只是为了与非常旧的程序兼容。 WebKit仍然会为document.all返回一个HTMLCollection类型,这就是为什么您注意到您的代码在Chrome浏览器中工作的原因。但是Firefox的现代版本故意决定放弃对它的支持,而是会返回undefined值。

这里建议的方法是使用的document.getElementById去的元素的引用,你想控制(你可以ID添加到第二对元素的),然后注册事件处理程序对这些元素从JavaScript。

1

document.all只适用于Firefox当页面处于怪癖模式(这是你绝对不想进入的东西)。

Don't use document.all

它是在W3C标准化之前创建的getElementById()

document.all是Microsoft Internet Explorer中

Source的专有功能。

改用现代的W3C兼容方法。

var checkbox = document.getElementById('my-checkbox'); 
document.getElementById('my-button').addEventListener('mouseover', function() { 
    checkbox.checked = true; 
}, false); 

...你需要做一些关于IE的attachEvent()的研究。

2

使用document.getElementById(id)代替document.all