<select> 上的 jQuery 更改事件不在 IE 中触发 [英] jQuery change event on <select> not firing in IE
问题描述
我有一个包含可变数量的 <select>
元素的页面(这解释了我在这里使用事件委托的原因).当用户更改所选选项时,我想隐藏/显示页面上的不同内容区域.这是我的代码:
I've got a page with a variable number of <select>
elements (which explains why I'm using event delegation here). When the user changes the selected option, I want to hide/show different content areas on the page. Here's the code I have:
$(document).ready(function() {
$('#container').change(function(e) {
var changed = $(e.target);
if (changed.is('select[name="mySelectName"]')) {
// Test the selected option and hide/show different content areas.
}
});
});
这在 Firefox 和 Safari 中有效,但在 IE 中不会触发更改事件.有谁知道为什么?谢谢!
This works in Firefox and Safari, but in IE the change event doesn't fire. Anyone know why? Thanks!
推荐答案
change
事件不会在 IE 中冒泡(请参阅 此处 和 此处).您不能同时使用事件委托.
The change
event does not bubble in IE (See here and here). You cannot use event delegation in tandem with it.
其实正是因为这个 IE 的 bug,jQuery .[live
不得不从 支持事件列表(仅供参考 DOM 规范声明 change
应该冒泡)
In fact, it is because of this IE bug that jQuery .[1]live
had to officially exclude change
from the list of supported events (FYI the DOM spec states change
should bubble)
关于您的问题,您可以直接绑定到每个选择:
With respect to your question, you can bind directly to each select:
$('#container select').change(/*...*/)
如果你真的想要事件委托,你可能尝试什么此人做到了 并且仅在 IE 中绑定到 click
,确实冒泡:
If you really want event delegation you might find some success trying what this person did and bind to click
in IE only, which does bubble:
$('#container').bind($.browser.msie ? 'click' : 'change', function(event) {
/* test event.type and event.target
* to capture only select control changes
*/
})
但是这个浏览器检测感觉真的不对.我真的会尝试使用前一个示例(直接绑定到下拉列表).除非你有数百个 框,否则事件委托在这里不会给你带来太多好处.
But this browser detection feels really wrong. I'd really try working with the former example (binding directly to the drop downs). Unless you have hundreds of <select>
boxes, event delegation wouldn't buy you much here anyway.
[1] 注意:jQuery >= 1.4 现在通过 <在 IE 中模拟冒泡 change
事件code>live()/on()
.
[1] Note: jQuery >= 1.4 now simulates a bubbling change
event in IE via live()
/on()
.
这篇关于<select> 上的 jQuery 更改事件不在 IE 中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!