javascript - 查找数据属性和复选框子项
问题描述
我希望你能看到我在这里想要做什么。我试图为 div 保持相同的结构,但单击顶部区域中的全选仅选择这 3 个,而底部全选仅选择底部 3。
显然有更好的方法可以做到这一点,但我已将我的代码剥离回这个基本示例。请帮我重写这一行:
$("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() {
所以我可以使用 profile-id 数据属性来选择该 div 内的复选框。
谢谢
$('.profile #select_all_cb').click(function() {
var profileID = $(this).closest('.profile').data('profile-id');
if($(this).is(":checked")) {
$("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() {
$(this).prop('checked', true);
});
} else {
$("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() { //Check all boxes
$(this).prop('checked', false);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profile" data-profile-id="1">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" id="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
<br /><br />
<div class="profile" data-profile-id="2">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" id="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
解决方案
ID 是唯一的,因此更改id="select_all_cb"
为class="select_all_cb"
.
单击.select_all_cb
时,向上查找.profile
父级,将复选框值作为布尔值存储在isChecked
变量中,并找到.score_alert_cb1
当前.profile
元素中的所有复选框。
$(".profile .select_all_cb").click(function() {
var profile = $(this).closest(".profile");
// var profileID = profile.data('profile-id');
var isChecked = $(this).is(":checked");
profile.find(".score_alert_cb1").prop("checked", isChecked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profile" data-profile-id="1">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" class="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
<br /><br />
<div class="profile" data-profile-id="2">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" class="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
推荐阅读
- python - 单例的哪种用法最合适/pythonic?
- c# - 文件流读取数组到行 C#
- python - Python numpy 方法/属性比 numpy 函数快吗?
- python - 如何使用 Selenium 更新 INITIAL_REDUX_STATE?
- javascript - 从 img 标签中检索值
- javascript - 父范围没有触发 React 中的子重新渲染
- spring - 从数据库动态更新权限(spring security)
- python - 如何使用 DLL 依赖项打包 Python 项目
- linux - Logitech MX 键的 Azerty 键盘布局错误 Linux 中的 Azerty 版本
- javascript - 如何通过在javascript中升序对我的数组进行排序