<select> 上的 jQuery 更改事件不在 IE 中触发 [英] jQuery change event on &lt;select&gt; not firing in IE

查看:25
本文介绍了<select> 上的 jQuery 更改事件不在 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 应该冒泡).[1]

In fact, it is because of this IE bug that jQuery live had to officially exclude change from the list of supported events (FYI the DOM spec states change should bubble).[1]

关于您的问题,您可以直接绑定到每个选择:

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
     */
})

但是这个浏览器检测感觉真的不对.我真的会尝试使用前一个示例(直接绑定到下拉列表).除非你有数百个

发送“验证码”获取 | 15天全站免登陆