5

我最近一直在使用许多复选框。我在点击事件中遇到了这个“问题”,.prevenDefault()我试图找到解决方案。就我而言,我希望能够决定是否可以根据其他字段选中/取消选中复选框。有时我什至不得不在事件触发之前打开一个对话框。这听起来比原来更容易......

这个 jsFiddle 中,您可以看到问题所在以及我如何尝试解决它(也请参见下面的代码)。大多数答案暗示使用更改而不是点击。但是你不能使用.preventdefault().

$('div').off('change','.wtf').on('change', '.wtf', function(e) {
    //e.preventDefault();
    //return false;
    if($(this).prop('checked') == true) {
        alert('I am true now, but I must stay false');
        $(this).prop('checked', false);
    }
    else {
        alert('I am false now, but I must stay true');
        $(this).prop('checked', true);
    }
});

这是最好的解决方案吗?或者有没有其他方法可以让复选框等到它被允许改变它的状态?

例如:只有当用户通过点击“确定”同意对话框中的消息时,我才希望取消选中该复选框。

4

2 回答 2

10

复选框是一种特殊情况,其中change事件和click可以相互替换,因为change event也可以通过单击复选框来触发。

click也就是说和之间唯一的大区别change.preventDefault(). 在使用除单击之外的任何其他方法更改复选框的值的情况下,更改事件会更好。

在这种情况下,您可以选择您喜欢的任何一个。一个例子是:Fiddle here

$('input[type="checkbox"]').on('change', function () {
    var ch = $(this), c;
    if (ch.is(':checked')) {
        ch.prop('checked', false);
        c = confirm('Do you?');
        if (c) {
            ch.prop('checked', true);
        }
    } else {
        ch.prop('checked', true);
        c = confirm('Are you sure?');
        if (c) {
            ch.prop('checked', false);
        }
    }
});
于 2013-04-25T11:21:17.547 回答
1

我已经实现了 Spokey解决方案,并基于使用returnif return 停止函数进行了一些修改confirm()true

$("input[name='status']").change(function(e){
       if ($(this).is(':checked')){
           msg = "{{__('The set status will be Active again! Are you sure?')}}"
           a = confirm(msg);
           if (a){
               return true;
           }
           $(this).prop('checked',false)
       }
       else{
           msg = "{{__('The set will be Inactive! Are you sure?')}}"
           a = confirm(msg);
            if (a){
               return true;
           }
           $(this).prop('checked',true);
       }
   })
于 2017-11-26T21:17:44.977 回答