JS:复选框链接到Span&背景颜色

时间:2013-03-13 15:59:18

标签: javascript jquery

我有两个复选框(见下文),点击后,激活跨度背景颜色的变化。问题是,我需要它,这样只能激活其中一个复选框,而另一个复选框被取消激活。我知道所有关于单选按钮的问题是,即使单选按钮停用,它也不会删除跨度的背景颜色。我需要一个只允许选择一个的解决方案,并在选择其他选项时自动删除背景颜色。

实施例: 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"));
    });

});

1 个答案:

答案 0 :(得分: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()从我们之前存储的复选框列表中删除当前复选框。 Example here

相关问题