onchange 事件的 ul 侦听器在 IE 中不起作用
我有一个 input
列表,
<ul id="list">
<li><input type="text" /></li>
<li><input type="text" /></li>
<li><input type="text" /></li>
<li><input type="text" /></li>
</ul>
因为有很多,所以我让 ul
做一个事件委托:
function addHandler(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
addHandler(document.getElementById("list"), "change", function(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target.nodeName === "INPUT") {
alert(target.value);
}
});
这在 Chrome、Firefox 中效果很好,但在 IE 中不行,这是什么?有问题吗?
小提琴:http://jsfiddle.net/94ngc/
I have a list of input
<ul id="list">
<li><input type="text" /></li>
<li><input type="text" /></li>
<li><input type="text" /></li>
<li><input type="text" /></li>
</ul>
Because there are many of them, I let ul
do a event delegation:
function addHandler(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, handler);
} else {
element["on" + type] = handler;
}
}
addHandler(document.getElementById("list"), "change", function(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target.nodeName === "INPUT") {
alert(target.value);
}
});
This works well in Chrome, Firefox, but not in IE, what's the problem?
Fiddle: http://jsfiddle.net/94ngc/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于
change
事件在 IE<9 中存在错误。看看这个图表:http://www.quirksmode.org/dom/events/ 如您所见, change
事件在所有浏览器中都有效,但 IE 仅在输入元素上触发它(我想它只是没有正确冒泡,或者它不适用于其他元素)。
尝试将此作为测试,它应该适用于 IE 中的第一个输入:
我建议您循环遍历所有输入并将侦听器附加到每个元素,而不是将事件委托给 UL,或者使用像 jQuery 或 YUI 这样的事件规范化器。
注意:您的代码似乎在 IE9+ 中运行良好
The problem is that the
change
event is buggy in IE<9. Have a look at this chart:http://www.quirksmode.org/dom/events/change.html
As you can see, the change event works in all browsers, but IE only triggers it on the input element (I suppose it just doesn’t bubble correctly, or it is not available for other elements).
Try this as a test, it should work for the fist input in IE:
I suggest you loop through all your inputs and attach the listener to each element instead of delegating the event to the UL, or use an event normalizer like jQuery or YUI.
Note: your code seems to work fine in IE9+