我被迫使用 IE8 (8.0.7601.17514),我有这个简单的页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<form action=".">
<input type="radio" name="rad" value="1" onchange="alert(1);"/>
<input type="radio" name="rad" value="0" onchange="alert(0);" checked="checked"/>
</form>
<a href="http://google.com">some dummy link</a>
</body>
</html>
我期望的是,当第二个单选按钮被选中时,单击第一个单选按钮将立即引发警报。这在 FF 中工作正常。
实际发生的是,当我点击第一个单选按钮时,没有任何反应。然后,当元素变得模糊时(例如,我点击其他地方、另一个 radio 、页面中的某个链接等),然后会引发警报。
有解决办法吗?
编辑:
显然这种行为完全符合 W3C spec
change
The change event occurs when a control loses the input focus and its value has been modified since gaining focus. This event is valid for INPUT, SELECT, and TEXTAREA. element.
(感谢@mu-is-too-short)。
解决方法是添加一个 onclick blur+focus:
function radioClick()
{
this.blur();
this.focus();
}
<input type="radio" name="rad" value="1" onclick="radioClick" onchange="alert(1);"/>
最佳答案
在 Internet Explorer 中(至少为 IE8)单击单选按钮或复选框以更改其值实际上不会触发 onChange 事件,直到输入失去焦点。
因此你需要自己以某种方式触发模糊事件..一个建议是有一个函数:如下:
function radioClick()
{
this.blur();
this.focus();
}
<input type="radio" name="rad" value="1" onclick="radioClick" onchange="alert(1);"/>
现在应该触发您的 onchange
事件,但正如您所见,它是冗余代码,因此您最好只使用 onclick
事件处理程序。
更好的解决方案是使用像 jquery 这样的现代 javascript 库,它可以为您处理所有这些怪癖。
关于javascript - 单选按钮上的 onchange 在 IE8 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10579019/