【问题标题】:Changing colour of unchecked checkbox text with jQuery使用 jQuery 更改未选中复选框文本的颜色
【发布时间】:2018-05-17 00:03:45
【问题描述】:

我希望更改未选中复选框的标签颜色。到目前为止,我的 jQuery 代码只允许选中一个复选框。有没有办法让未选中的复选框标签文本在选择/选中另一个选项时变为不同的颜色?这是我的 HTML:

              <label><input class="oneBox" type="checkbox" >Wednesday June 6th</label>

              <label><input class="oneBox" type="checkbox" >Friday June 8th</label>

这里是只检查一个框的 jQuery:

      $(document).ready(function(){
           $('.oneBox').on('change', function() {
               $('.oneBox').not(this).prop('checked', false);
                    $('#result').html($(this).data( "id" ));

      if($(this).is(":checked"))
           $('#result').html($(this).data( "id" ));
      });
  });

谢谢!

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

 $(document).ready(function(){
           $('label').addClass('default');
           $('.oneBox').on('change', function() {
            $('.oneBox').not(this).parents('label').removeClass("checked").addClass('oneBox');
            // $('.oneBox').attr('class', 'oneBox');
               $('.oneBox').not(this).prop('checked', false);
               $(this).parents('label').removeClass("oneBox").addClass("checked");
              
      if($(this).is(":checked"))
           $('#result').html($(this).data( "id" ));
          
      });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.default {
 color: blue;
}
.checked {
color: red;
}
</style>
<label>
<input class="oneBox" type="checkbox" data-id="Wednesday" >Wednesday June 6th</label>
              <label ><input class="oneBox" type="checkbox" data-id="Friday" >Friday June 8th</label>
              
<div id="result"></div>

【讨论】:

    【解决方案2】:

    您需要做的就是将 .parent() 设置为您想要的颜色。这可以通过使用 .css() 来完成,例如 $('.oneBox').not(this).parent().css('color', 'red')。请注意,如果您更改选择,在这种情况下,第一个选择将保持红色。为了防止这种情况,您还需要使用$(this).parent().css('color', 'inherit') 将颜色告诉inherit

    这可以在下面看到:

    $(document).ready(function() {
      $('.oneBox').on('change', function() {
        $('.oneBox').not(this).prop('checked', false);
        //$('#result').html($(this).data("id"));
        if ($(this).is(":checked")) {
          //$('#result').html($(this).data("id"));
          $('.oneBox').not(this).parent().css('color', 'red');
          $(this).parent().css('color', 'inherit');
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <label><input class="oneBox" type="checkbox">Wednesday June 6th</label>
    <label><input class="oneBox" type="checkbox">Friday June 8th</label>

    【讨论】:

    • 不太确定为什么这会被否决,因为它直接解决了 OP 提出的问题。如果您让我知道您认为它有什么问题,很高兴改进答案。
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 2013-02-19
    • 2018-04-24
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多