复选框& # 39;改变# 39;事件在单击标签时起作用.ie8, ie7

Checkbox 'change' event works when click the label . in ie8, ie7

本文关键字:起作用 ie8 标签 ie7 改变 事件 复选框 单击      更新时间:2023-09-26

在我的表单中,我有一个CheckBox,我有一个标签CheckBox。在firefox &在IE9中,复选框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>

My 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();
    }
});

仅供将来参考,据我所知,"change"事件在旧版本的IE中有点错误。

你必须使用propertychange事件在IE中得到它的行为如预期的。我喜欢使用的代码是:

Edit 2 (back to core)

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

编辑1(有bug,不可靠)

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

此代码已更新为使用jQuery 1.9+,并在注释中使用马吕斯的一些输入。

原始(弃用)

以下是使用旧版本jQ的旧代码:

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