javascript - 单选按钮上的 onchange 在 IE8 中无法正常工作

标签 javascript html internet-explorer radio-button

我被迫使用 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/

相关文章:

javascript - IE10/IE11 清除缓存后中止 Post Ajax 请求,错误为 "Network Error 0x2ef3"

javascript - 在 Sequelize 中使用具有多对多关系的 AND 操作

internet-explorer - Calendly 小部件在 IE 中不起作用(Angular 应用程序)

html - CSS3 转换在 Microsoft Edge(和 IE)中显示不佳

Javascript 字符串到 IE 的 html 问题

javascript - JSX 元素类型 'void' 不是 JSX 元素的构造函数

javascript - JavaScript中代码注释的正确方式是什么

javascript - 我如何使用 javascript 和 DOM 正确搜索和替换 HTML 文档中的字符串?

javascript - 如何突出显示拖动文件的唯一 div?

java - 小程序标签后备/替代内容