【问题标题】:Simulate radio buttons using checkboxes and only trigger change event once?使用复选框模拟单选按钮并且只触发一次更改事件?
【发布时间】:2013-01-15 22:55:34
【问题描述】:

我想使用复选框来模拟单选按钮的行为,这表示:

当一个复选框被选中时,所有其他同名的复选框(这里是选择器)都被取消选中

但是,如果我尝试做类似的事情:

$('body').delegate('.myradio', 'click', function(e) {
    $('.myradio').prop('checked', false);
    $(this).prop('checked', true);
});

这会触发两次change 事件。

如果我尝试添加 e.preventDefault

$('body').delegate('.myradio', 'click', function(e) {
    $('.myradio').prop('checked', false);
    $(this).prop('checked', true);
    e.preventDefault();
});

根本没有触发任何事件,也没有选中复选框。

最后,如果我尝试自己触发事件:

$('body').delegate('.myradio', 'click', function(e) {
    $('.myradio').prop('checked', false);
    $(this).prop('checked', true);
    e.preventDefault();
    $(this).change();
});

change 事件也被调用了两次。

关于信息,我所有的复选框都有唯一的 ID。

除了选中的复选框之外,禁用所有复选框的正确方法是什么?

【问题讨论】:

  • 这可能是一个显而易见的问题,但是如果您希望复选框的行为类似于单选按钮,为什么不直接使用单选按钮?
  • 因为该行为取决于其他地方检查的内容:在某些情况下,用户可能能够检查多个复选框。
  • 您可以使用超时并忽略触发的事件,例如100 毫秒内两次,但这真的很脏;)
  • 不错的主意。 0 毫秒的超时完成了这项工作。 :-)
  • @Ninsuo 那么你应该能够取消选中一个复选框吗?

标签: jquery checkbox radio-button


【解决方案1】:

如果我正确理解您的问题,以下应该可以工作。

$('body').delegate('.myradio', 'click', function (e) {
    var $element = $(this)[0];
    $('.myradio').each(function () {
        if ($(this)[0] !== $element)
            $(this).prop('checked', false);
    });
});

这样,复选框组的行为类似于单选按钮组。除了您可以取消选择一个选定的项目。


下面的代码使该组的行为更像一个无线电组。选择后无法取消选择。
$('body').delegate('.myradio', 'click', function (e) {
    var $element = $(this)[0];

    if ($(this).prop('checked') == false) {
        $(this).prop('checked', true);
        return;
    }

    $('.myradio').each(function () {
        if ($(this)[0] !== $element)
            $(this).prop('checked', false);
    });
});

【讨论】:

    【解决方案2】:

    如果您仍然希望能够取消选中复选框,您可以这样做

    $('input[type=checkbox]').change(function(){ // <-- use the change event
      var group = $(this).attr('name'); // get the group
      $('input[name='+group+']').not(this).prop('checked',false);  // set others to unchecked
    });
    

    http://jsfiddle.net/rmJpB/

    【讨论】:

      【解决方案3】:

      你可以使用 on() 函数。

      $('body').on('click', '.myradio', function(){
        $('.myradio[name="'+$(this).attr('name')+'"]').prop('checked', false);
        $(this).prop('checked', true);
      });
      

      取消选中所有其他同名复选框,选中当前复选框。

      http://jsbin.com/ofibow/2/edit

      【讨论】:

        猜你喜欢
        • 2012-07-14
        • 1970-01-01
        • 2011-12-24
        • 2013-07-19
        • 2016-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多