简体   繁体   English

jQuery .click()在自定义函数之前执行默认操作

[英]jQuery .click() perform the default action before the custom function

Here is my code, I have two checkboxes and want to keep one disabled until the other one is enabled: 这是我的代码,我有两个复选框,并希望保持禁用状态,直到另一个启用:

$(function(){
    $('#remember').live('click', function(event){
        if($('#remember').is(':checked')){
            $('#keepIn').removeAttr('disabled');
        }
        else
            $('#keepIn').attr('disabled', 'disabled');
    });
});

The problem is that this function executes before the default action and when I click in the first one $('#remember').is(':checked') returns false (the old value) instead of true. 问题在于此函数在默认操作之前执行,并且当我单击第一个$('#remember').is(':checked')返回false(旧值)而不是true。

You can use change event instead: 您可以改为使用change事件:

$('#remember').live('change', function(event) {
    if (this.checked) {
        $('#keepIn').removeAttr('disabled');
    } else {
        $('#keepIn').attr('disabled', 'disabled');
    }
});

DEMO: http://jsfiddle.net/jP3NY/ 演示: http : //jsfiddle.net/jP3NY/


NB: live method is deprecated. 注意:不建议使用live方法。 You should better use on or delegate . 你应该更好地利用ondelegate

For the newer version of jQuery the solution could be as follows: 对于较新版本的jQuery,解决方案如下:

$('body').on('change', '#remember', function(event) {
    $('#keepIn').prop('disabled', !this.checked);
});

Instead of body you can use any parent element of #remember . 除了body您可以使用#remember任何父元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM