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. 如果我选择其他单选按钮,警报将不再起作用。

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


侃侃无极
浏览 113回答 2
2回答

繁花不似锦

如果您希望在选中或取消选中复选框时更改类,则需要一个事件处理程序。处理程序可以检查每个 LI 是否包含选中的按钮。$(".wc_payment_method :radio").click(function() {&nbsp; $(".wc_payment_method").each(function() {&nbsp; &nbsp; $(this).toggleClass("is-checked", $(this).find(":radio:checked").length > 0);&nbsp; });});.is-checked {&nbsp; background-color: pink;}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><ul>&nbsp; <li class="wc_payment_method payment_method_paypal">&nbsp; &nbsp; <input id="payment_method_paypal" type="radio" class="input-radio" name="payment_method" value="paypal">&nbsp; &nbsp; <label for="payment_method_paypal">PayPal</label>&nbsp; </li>&nbsp; <li class="wc_payment_method payment_method_credit">&nbsp; &nbsp; <input id="payment_method_credit" type="radio" class="input-radio" name="payment_method" value="credit">&nbsp; &nbsp; <label for="payment_method_paypal">Credit Card</label>&nbsp; </li></ul>

拉风的咖菲猫

您的代码仅向输入标记添加一个类。要在单击事件上添加特定类,您必须使用 jquery 中的 $().click 方法。jQuery(function ($) {function addClass() {&nbsp; &nbsp; $(".wc_payment_method input:checked").each(function() {&nbsp; &nbsp; &nbsp; &nbsp; $(this).closest('li').addClass('yourClass');&nbsp; &nbsp; &nbsp; &nbsp; $(this).addClass("is-checked");&nbsp; &nbsp; &nbsp; &nbsp; alert(this.id + " is checked");&nbsp; &nbsp; });}addClass();$(".wc_payment_method input").click(function(){&nbsp; &nbsp; addClass();});});<script&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; src="https://code.jquery.com/jquery-3.5.0.min.js"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; crossorigin="anonymous"></script><ul><li class="wc_payment_method payment_method_paypal">&nbsp; &nbsp; <input id="payment_method_paypal" type="radio" class="input-radio" checked name="payment_method" value="paypal">&nbsp; &nbsp; <label for="payment_method_paypal">PayPal</label></li><li class="wc_payment_method payment_method_paypal1">&nbsp; &nbsp; <input id="payment_method_paypal1" type="radio" class="input-radio" name="payment_method1" value="paypal2">&nbsp; &nbsp; <label for="payment_method_paypal1">PayPal</label></li></ul>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5