【问题标题】:jQuery radio button checked, else statement not working选中 jQuery 单选按钮,else 语句不起作用
【发布时间】:2017-12-09 08:48:40
【问题描述】:

我希望输入在选中时更改其样式(添加背景颜色)。这是有效的,但是,在未检查输入单选类型时删除背景颜色的 else 语句不起作用。

已经尝试了各种不同的方法,但是当您单击不同的输入时无法触发 else 语句。

HTML:

<tr style="color:white;">
<td id="test" style="background-color:rgb(153, 117, 82);" value="1">
<label><input type="radio" name="c0" class="c0" value="10" onclick="output();" id="t"/>1</label>
</td>
</tr>

<tr style="color:white;">
<td style="background-color: rgb(255, 57, 57);">
<label><input type="radio" name="c0" class="c0" value="20" onclick="output();" id="t"/>2</label>
</td>

JS:

$('input#t').on("click", function() {
if ($("input#t").is(':checked')) {
    $(this).parent().addClass("active");
} 
    else {
    $(this).parent().removeClass("active");
}
});

codepen:https://codepen.io/Not_A_Fax_Machine/pen/zzRMNZ/

【问题讨论】:

  • 问题是因为您有两个具有相同id 属性的元素 - 它们必须是唯一的。
  • 也试过 - $('input[type=radio], input[type=checkbox]').on("click", function() { if ($(this).is( ':checked')) { $(this).parent().addClass("active"); } else { $(this).parent().removeClass("active"); } }); - 因此没有 ID,就没有成功。

标签: javascript jquery input radio-button


【解决方案1】:

问题在于您有两个具有相同 id 属性的元素 - 它们必须是唯一的。

要解决此问题,请使用类对单选按钮进行分组,然后使用 this 关键字来引用 change 事件处理程序中的元素。试试这个:

$('.t').on("change", function() {
  $('label').removeClass('active');
  $(this).parent().toggleClass('active', this.checked);
  // output();
});
tr {
  color: white;
}

td.foo {
  background-color: rgb(153, 117, 82);
}

td.bar {
  background-color: rgb(255, 57, 57);
}

.active {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="foo">
      <label><input type="radio" name="c0" class="t c0" value="10" />1</label>
    </td>
  </tr>
  <tr>
    <td class="bar">
      <label><input type="radio" name="c0" class="t c0" value="20" />2</label>
    </td>
  </tr>
</table>

注意删除内联样式,应该避免。

【讨论】:

  • 不幸的是仍然没有运气。
  • 你能扩展一下吗?什么发生/不发生?控制台中的任何错误?从上面的 sn-p 中可以看出,考虑到问题中的示例代码,它可以正常工作
  • 用户错误!非常感谢,一直坚持这个!
猜你喜欢
  • 2016-07-14
  • 2016-03-19
  • 2016-02-04
  • 1970-01-01
  • 2014-05-31
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
相关资源
最近更新 更多