jQuery: 查找数据属性具有特定值的元素

jQuery: find elements where data attribute is has a specific value

我有一个主复选框 Select all 以及一个按钮,可以恢复到加载时的原始状态。页面加载后,我将数据 属性 绑定到每个复选框,如果有加载为选中或未选中。

$('input[type="checkbox"]').each((i, e) => {
    if($(e).is(':checked'))
       $(e).data('default', true);
});

$('.js-select-all').on('mouseup', () => {
    $('input[type="checkbox"]').prop('checked', true);
});

我需要找到 checkboxes,其中 data 属性 称为 defaulttrue 并再次标记它们已选中。

$('.js-revert').on('mouseup', () => {
    $('input[type="checkbox"]').data('default', true).prop('checked', true);
});

我知道可以用 each 循环和 condition 来完成。但问题是我必须通过所有复选框才能这样做。因此,我正在寻找一种更快的方法,因为应用程序中已经有几十个复选框。

如果您只使用 jQuery,除了遍历所有复选框之外,没有更快的方法来检查存储在复选框中的 .data()

但如果您使用的是 jQueryUI,则可以使用此处显示的 :data() 选择器:

https://api.jqueryui.com/data-selector/

然后你可以使用

$(':checkbox:data(default)').prop('checked', true);