jQuery 复选框更改和单击事件

13 浏览
0 Comments

jQuery 复选框更改和单击事件

$(document).ready(function() {
  //set initial state.
  $('#textbox1').val($(this).is(':checked'));
  $('#checkbox1').change(function() {
    $('#textbox1').val($(this).is(':checked'));
  });
  $('#checkbox1').click(function() {
    if (!$(this).is(':checked')) {
      return confirm("Are you sure?");
    }
  });
});



这里,.change() 用来更新复选框状态的文本框值。我使用 .click() 来确认取消选中。如果用户选择取消,则会还原复选框状态,但此时 .change() 已在确认前触发。

这会导致状态不一致,即当已选中复选框时,文本框显示“false”。

我该如何处理取消选中并使文本框值与选中状态保持一致?

admin 更改状态以发布 2023年5月22日
0
0 Comments

示例

使用 mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});

0
0 Comments

JSFiddle中测试过,能够完成你所要求的功能。这种方法的额外好处是当与复选框相关联的标签被点击时,会触发事件。

更新的答案:

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val(this.checked);
    $('#checkbox1').change(function() {
        if(this.checked) {
            var returnVal = confirm("Are you sure?");
            $(this).prop("checked", returnVal);
        }
        $('#textbox1').val(this.checked);        
    });
});

原始答案:

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));
    $('#checkbox1').change(function() {
        if($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
        $('#textbox1').val($(this).is(':checked'));        
    });
});

0