jQuery 代码在选中复选框时有效,但在未选中时无效
jQuery code works when a checkbox is selected but doesn't work when unchecked
我有一个 jQuery 函数,可以在选中时更改 <div>
的颜色。如果不选中,则没有背景。当它被检查时,它应该是黑色的。选中时有效,取消选中时无效。
这是我目前所做的:
$(document).on('change', '#two_img_left_feature_img label.selected input', function () {
if ($("#two_img_left_feature_img label.selected input").is(":checked")) {
$('#two_img_left_feature_img').css('background','black');
} else {
$('#two_img_left_feature_img').css('background','white');
}
});
HTML很简单:
<div id="two_img_left_feature_img">
<input type="checkbox" id="acf-block_60173d68d2c6a-field_5f8cf27e7c048-two_img_left_set_featured_img" name="acf-block_60173d68d2c6a[field_5f8cf27e7c048][]" value="two_img_left_set_featured_img">
</div>
问题是关于 label.selected
...当复选框未选中时,我猜标签没有 .selected
class.
因此只需从事件处理程序选择器和条件中删除 label.selected
。太具体了...
$(document).on("click", "#two_img_left_feature_img input", function () {
if ($("#two_img_left_feature_img input").is(":checked")) {
$("#two_img_left_feature_img").css("background", "black");
} else {
$("#two_img_left_feature_img").css("background", "white");
}
});
#two_img_left_feature_img {
height: 200px;
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="two_img_left_feature_img">
<label>
<input type="checkbox" id="acf-block_60173d68d2c6a-field_5f8cf27e7c048-two_img_left_set_featured_img" name="acf-block_60173d68d2c6a[field_5f8cf27e7c048][]" value="two_img_left_set_featured_img">
</label>
</div>
我有一个 jQuery 函数,可以在选中时更改 <div>
的颜色。如果不选中,则没有背景。当它被检查时,它应该是黑色的。选中时有效,取消选中时无效。
这是我目前所做的:
$(document).on('change', '#two_img_left_feature_img label.selected input', function () {
if ($("#two_img_left_feature_img label.selected input").is(":checked")) {
$('#two_img_left_feature_img').css('background','black');
} else {
$('#two_img_left_feature_img').css('background','white');
}
});
HTML很简单:
<div id="two_img_left_feature_img">
<input type="checkbox" id="acf-block_60173d68d2c6a-field_5f8cf27e7c048-two_img_left_set_featured_img" name="acf-block_60173d68d2c6a[field_5f8cf27e7c048][]" value="two_img_left_set_featured_img">
</div>
问题是关于 label.selected
...当复选框未选中时,我猜标签没有 .selected
class.
因此只需从事件处理程序选择器和条件中删除 label.selected
。太具体了...
$(document).on("click", "#two_img_left_feature_img input", function () {
if ($("#two_img_left_feature_img input").is(":checked")) {
$("#two_img_left_feature_img").css("background", "black");
} else {
$("#two_img_left_feature_img").css("background", "white");
}
});
#two_img_left_feature_img {
height: 200px;
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="two_img_left_feature_img">
<label>
<input type="checkbox" id="acf-block_60173d68d2c6a-field_5f8cf27e7c048-two_img_left_set_featured_img" name="acf-block_60173d68d2c6a[field_5f8cf27e7c048][]" value="two_img_left_set_featured_img">
</label>
</div>