0

我有两个复选框(见下文),单击它们时,激活跨度背景颜色的更改。问题是,我需要这样才能激活这些复选框中的一个,而取消激活另一个。我对单选按钮了如指掌,问题是即使单选按钮停用,它也不会删除跨度的背景颜色。我需要一个只允许选择一个,并在选择另一个选项时自动删除背景颜色的解决方案。

示例: http ://eblacksmith.com/test/

核心代码:

$(document).ready(function() {

$("span[class='checkbox']").addClass("unchecked");

    $(".checkbox").click(function(){

        if($(this).children("input").attr("checked")){  
            // uncheck
            $(this).children("input").attr("checked", false);
            $(this).removeClass("checked");
            $(this).addClass("unchecked");
        }else{
            // check
            $(this).children("input").attr("checked", true);
            $(this).removeClass("unchecked");
            $(this).addClass("checked");
        }

        //alert($(this).children("input").attr("checked"));
    });

});
4

1 回答 1

0

以下应该工作

 $(document).ready(function() {

   // get a list of all the checkboxes
   var $checkboxEls = $('input[type="checkbox"]');

   $(document).on('change', 'input[type="checkbox"]', function(event) {

     // highlight this check box
     $(this).parent('span').addClass('checked');

     // remove other classes
     $checkboxEls.not(this).removeAttr('checked').parent('span').removeClass('checked');

   });
 });

它利用not()从我们之前存储的复选框列表中删除当前复选框。这里的例子

于 2013-03-13T16:20:35.900 回答