【问题标题】:Checkbox 'change' event works when click the label . in ie8, ie7单击标签时复选框“更改”事件有效。在 ie8、ie7
【发布时间】:2011-11-04 06:02:11
【问题描述】:

在我的表单中,我有一个CheckBox,并且我有一个 CheckBox 的标签。在 Firefox 和 IE9 中,CheckBox change event 按预期工作,但在 IE8 和 IE7 中,单击标签而不是复选框时会触发事件。

我的 HTML

<div class="item-container">
    <div class="label-container">
    </div>
    <div class="textbox-container">
        <input id="AddNewProductCategory" class="" type="checkbox" width="20px" height="20px"
            value="1" name="addnewproductcategory" tabindex="1900" />
    </div>
    <div class="after-checkbox-label">
        <label class="Verdana11-424039" for="AddNewProductCategory">
            Add New Service Category</label>
    </div>
</div>

我的 jQuery

jq('#AddNewProductCategory').change(function(){
    jq('#CategoryName').next('label[for=CategoryName]').remove();
    jq('#Category').next('label[for=Category]').remove();

    if (!jq('#AddNewProductCategory').is(':checked')) {
         alert("in change");
        jq('input[name="newcategory"]').val('');
        jq('#CategoryName').hide();     
        jq('#store_category').hide();
        jq('#Category').removeAttr('disabled');

    }
    else {
        jq('#Category').attr('disabled', 'disabled');
        jq('#CategoryName').show();     
        jq('#store_category').show();
    }
});

【问题讨论】:

  • 你有什么版本的jquery?
  • 根据本文档api.jquery.com/change:“从 jQuery 1.4 开始,更改事件在 Internet Explorer 中冒泡,其行为与其他现代浏览器中的事件一致。”考虑更改 jquery 版本。
  • 如果有帮助请告诉我们
  • hmmm............我将“更改”事件更改为“点击”事件,现在它可以工作了,谢谢大家
  • 只是一个提示 - 不要在此处粘贴代码,将其添加到 jsfiddle 并给我们链接。活生生的例子更好。

标签: javascript jquery html css


【解决方案1】:

仅供参考,据我记得,“更改”事件在旧版本的 IE 中有点错误。

您必须在 IE 中使用propertychange 事件才能使其按预期运行。我喜欢使用的代码是:

编辑 2(回到核心)

$(element).on(navigator.userAgent.match(/msie/i) ? "propertychange" : "change", function(evt) {
    evt.preventDefault();
    // Your code here
});

编辑 1(有问题,不可靠)

$(element).on(!$.support.changeBubbles ? "propertychange" : "change", function(evt) {
    evt.preventDefault();
    // Your code here
});

此代码已更新为与 jQuery 1.9+ 一起使用,其中一些来自 cmets 中 Marius 的输入。

原始(已弃用)

以下是旧版 jQ 的旧代码:

$(element).bind($.browser.msie ? 'propertychange' : 'change', function(evt) {
    evt.preventDefault();
    // Your code here
});

【讨论】:

  • 对于那些还得支持IE8的人,即使在2013年,我发现IE9及以上都不会出现这个问题。所以我使用($.browser.msie &amp;&amp; $.browser.version &lt; 9) 进行检查。
  • $.browser 现在在 jquery 1.9+ 中已弃用。您可以将其替换为 if (!$.support.changeBubbles)。
  • 谢谢 Marius,我一直在寻找那行代码的更新——我所拥有的最好的是(为了简单起见)/msie/.test(navigator.userAgent.toLowerCase())
猜你喜欢
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
相关资源
最近更新 更多