单击CSS jQuery

时间:2018-05-04 20:16:06

标签: jquery html css button radio

目前,我在点击单选按钮时尝试更改文字颜色。这是有效的,但只要选择了另一个,它就必须改回来。无论我尝试什么,我都无法让它发挥作用。我认为这是解决问题的最好方法。

这是我目前正在使用的代码:(单选按钮)

<div class="checkboxes">
<label class="container"><div class="checkboxcijfer">1</div>
  <input type="radio" name="radio">
  <span class="checkmark"></span>
</label>

<label class="container"><div class="checkboxcijfer">2</div>
  <input type="radio" name="radio">
  <span class="checkmark"></span>
</label>

jQuery(我已经删除了我尝试过的所有内容。我按照教程删除了兄弟姐妹的课程。不幸的是,这不起作用。这会使项目的颜色发生变化:

    $(function() {
    $('.container [type="radio"]').on('change', function() {

        $(this).prev().addClass('red')

    });
    });

简单的CSS:

.white
        {
            color: #FFF;
        }

So here is how it currently works

And this is what's going wrong when clicking away.

1 个答案:

答案 0 :(得分:0)

找到类.red的元素,然后删除类:

$(function() {
  $('.container [type="radio"]').on('change', function() {
    $('.red').removeClass('red');
    $(this).prev().addClass('red')

  });
});
.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
  <label class="container">
    <div class="checkboxcijfer">1</div>
    <input type="radio" name="radio">
    <span class="checkmark"></span>
  </label>

  <label class="container">
    <div class="checkboxcijfer">2</div>
    <input type="radio" name="radio">
    <span class="checkmark"></span>
  </label>
</div>

如果您可以切换inputdiv,则可以使用adjacent sibling selector获得仅限CSS的解决方案:

input:checked + .checkboxcijfer {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkboxes">
  <label class="container">
    <input type="radio" name="radio">
    <div class="checkboxcijfer">1</div>
    <span class="checkmark"></span>
  </label>

  <label class="container">
    <input type="radio" name="radio">
    <div class="checkboxcijfer">2</div>
    <span class="checkmark"></span>
  </label>
</div>