4

This is the part of the code for one of the radio buttons:

$("#new").click(function(){
    if( $('#new').is(':checked') )
        $.jGrowl("You already have this option selected!", life: 1500});
    else
        changeOption(1);
});

Now, I understand that the else part will never run, because the radio button will be already checked on click event. What I'm wondering is, is there an event which would let me capture the state of the radio button (which is about to be clicked) and therefor determine if he is not yet clicked, and if so change the option to this newly selected one.

4

4 回答 4

6

将初始值存储在数据属性中,并将其用于更改:

$.each($("input[type='radio']"), function(i,e) {
    $(e).data('check', e.checked);
});

$("#new").on('click keyup', function(){
    if( $(this).data('check') ) {
        alert("You already have this option selected!");
    }else{
        alert("This option is unselected");
    }
    $(this).data('check', this.checked);
});​

小提琴

甚至适用于键盘事件。

于 2012-08-28T12:38:58.003 回答
4

请改用 mouseup 事件。

$("#new").mouseup(function(){
    if( $('#new').is(':checked') )
        $.jGrowl("You already have this option selected!", life: 1500});
    else
        changeOption(1);
});

小提琴

编辑
即使 mouseup 事件有效,使用 mousedown 事件似乎更合乎逻辑。这是那个小提琴

于 2012-08-28T13:09:42.533 回答
2

mousedown 事件应该可以工作。它在单击元素时触发,在释放鼠标按钮之前。

于 2012-08-28T12:31:11.197 回答
0

如果它可能未被选中,为什么不直接取消选中它?

$("#new").click(function(){
    if( $('#new').is(':checked') ){
        $.jGrowl("You already have this option selected!", life: 1500});
        $('#new').attr('checked', false);
    } else {
        changeOption(1);
        $('#new').attr('checked', true);
    }
});
于 2012-08-28T12:36:33.277 回答