这是其中一个单选按钮的代码部分:
$("#new").click(function(){
if( $('#new').is(':checked') )
$.jGrowl("You already have this option selected!", life: 1500});
else
changeOption(1);
});
现在,我知道else
部分永远不会运行,因为单选按钮将在单击事件时被选中。我想知道的是,是否有一个事件可以让我捕捉单选按钮(即将被点击)的状态,从而确定他是否还没有被点击,如果是,请将选项更改为新选择的选项。
将初始值存储在数据属性中,并在更改时使用:
$.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);
});
FIDDLE
甚至可以处理键盘事件。
请改用mouseup事件。
$("#new").mouseup(function(){
if( $('#new').is(':checked') )
$.jGrowl("You already have this option selected!", life: 1500});
else
changeOption(1);
});
小提琴。
编辑
尽管mouseup事件有效,但使用mousedown事件似乎更合乎逻辑。这是小提琴。
mousedown事件应该可以工作。它在单击元素时触发,然后再释放鼠标按钮。
如果可能没有选中,为什么不直接取消选中它?
$("#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);
}
});