首页 > 解决方案 > jQuery:如果 LI 已选中单选框,则添加类

问题描述

我想添加一个类,<li>如果它包含一个选中的单选按钮。

这是我当前的 HTML 结构:

<li class="wc_payment_method payment_method_paypal">
    <input id="payment_method_paypal" type="radio" class="input-radio" name="payment_method" value="paypal">
    <label for="payment_method_paypal">PayPal</label>
</li>

这是我迄今为止尝试过的:

<script>
    jQuery(function ($) {
        $(".wc_payment_method :checked").each(function() {
            $(this).addClass("is-checked");
            alert(this.id + " is checked");
        });
    });

</script>

警报有效。<li>它使用选中的单选按钮显示正确的项目。但是有两个问题我无法解决。

  1. 脚本不会is-checked在页面加载时添加类
  2. 如果我选择其他单选按钮,警报将不再起作用。

有人能把我推向正确的方向吗?

标签: javascripthtmljquerycss

解决方案


如果您希望在选中或取消选中这些框时更改类,则需要一个事件处理程序。处理程序可以检查每个 LI 是否包含一个选中按钮。

$(".wc_payment_method :radio").click(function() {
  $(".wc_payment_method").each(function() {
    $(this).toggleClass("is-checked", $(this).find(":radio:checked").length > 0);
  });
});
.is-checked {
  background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="wc_payment_method payment_method_paypal">
    <input id="payment_method_paypal" type="radio" class="input-radio" name="payment_method" value="paypal">
    <label for="payment_method_paypal">PayPal</label>
  </li>
  <li class="wc_payment_method payment_method_credit">
    <input id="payment_method_credit" type="radio" class="input-radio" name="payment_method" value="credit">
    <label for="payment_method_paypal">Credit Card</label>
  </li>
</ul>


推荐阅读