javascript - 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>
它使用选中的单选按钮显示正确的项目。但是有两个问题我无法解决。
- 脚本不会
is-checked
在页面加载时添加类 - 如果我选择其他单选按钮,警报将不再起作用。
有人能把我推向正确的方向吗?
解决方案
如果您希望在选中或取消选中这些框时更改类,则需要一个事件处理程序。处理程序可以检查每个 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>
推荐阅读
- jquery - Onclick 事件到表 tr 元素并阻止事件到按钮、复选框
- php - AppIdentityService::getApplicationId 返回“无”
- python - 迫切需要有关转换日期列的建议
- c - 在 C 中返回带有字符串值的结构
- django - 将字典类型数据添加到下拉列表(选择表单元素)
- python - Wxpython 面板被裁剪,左上角仅显示一个小框
- assembly - 如何让`mov rdx,symbol`在clang intel-syntax中移动符号值而不是符号地址的值?
- apache-flink - 由于背压导致的检查点超时
- amazon-web-services - 无法取消标记 AWS 资源
- google-apps-script - Saving data from Google Spreadsheet into an Array