【问题标题】:Is it possible to solve this situation with JavaScript/jQuery? [duplicate]是否可以使用 JavaScript/jQuery 解决这种情况? [复制]
【发布时间】:2019-10-12 18:52:07
【问题描述】:

我有一个代码可以检查单选按钮是否被选中以及是否设置了背景颜色。一切正常,我的问题是当我想选择另一个单选按钮时,结果是我所有的单选按钮都在点击时被选中,但它需要只是一个。

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio">
<input type="radio" checked>

你可以测试一下。只需尝试选择另一个单选按钮,您将看到已选择单选按钮(2 个单选按钮)。

我想要实现的是,当您单击另一个单选按钮时,它需要删除这个选中的类或任何其他想法。我无法在单选按钮之间切换。

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

给他们同样的name:

$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css("background", "yellow");
  }
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input type="radio" name="radio">
<input type="radio" name="radio" checked>

【讨论】:

  • 没有名字也可以吗?
  • 不,不是@jomskris。
【解决方案2】:

单选按钮可以很容易地使用下面的代码中的名称属性来处理,可能会对您有所帮助

<input type="radio" name="color">
<input type="radio"  name="color" checked>

$("input[name='color']").each(function () {
    if ($(this).is(":checked")) {
      $(this).css("background", "yellow");
    }
});

【讨论】:

  • 没有名字也可以吗?
【解决方案3】:
<input type="radio" name="sameName">
<input type="radio" name="sameName">

这样设置他们的名字

【讨论】:

    【解决方案4】:

    要在每个单选按钮的可见背景颜色上实现所需的行为,您可以使用 span 元素包装每个单选 &lt;input /&gt;,这将实现单选按钮背景颜色的视觉效果:

    /* Reusable selection of radio buttons */
    const radioButtons = $("input[type='radio']");
    
    /* Updates selected radio button parent backgrounds based on checked state */
    function updateBackground() {
      radioButtons.each(function() {
        $(this).parent().css('background', $(this).is(":checked") ? 'yellow' : '');
      });
    }
    
    /* Attach click behavior to each causing the background colors to update */
    radioButtons.click(updateBackground);
    
    /* Initalise the backgrounds and */
    updateBackground();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <!-- Wrap each radio button with a span, which will be used to show a colored background 
    when the radio button is checked -->
    <span>
      <input type="radio" name="radio-group-name" checked>
    </span>
    <span>
      <input type="radio" name="radio-group-name">
    </span>

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 2017-12-11
      • 2013-03-23
      • 2019-01-01
      • 2015-05-16
      • 1970-01-01
      相关资源
      最近更新 更多