jquery 中的 Select 个元素使用变量按值收集

Select element in jquery collection by value using variable

我正在使用 jQuery 并且有一个包含页面输入的集合(对象?)。我有一个变量,它保存循环的每次迭代的值属性。我想找到值与我的变量匹配的输入,以便我可以选中复选框。

function reject(el) {
    const checkBox = $(el).find('input:checkbox');
    if (tempStore.checks.length > 0) {
        for (let j=0;j<tempStore.checks.length;j++) {
            $(checkBox).find("input.val("+tempStore.checks[j]+")").checked = true;
        }
    }
}

我已经在线搜索了几个小时,但找不到正确的语法。有人可以帮忙吗?

如果值在 DOM 中设置,您可以尝试 select 通过 attribute[value=""] select 或者:

let value = "A";

$('body').find('input[value="' + value + '"]').prop("checked", "checked");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="A">

请注意,在您的代码中您可以执行以下操作:

checkBox.filter(...)

这将提高性能,因为它会 filter an already filled element list, instead of find

另一个解决方案(不是最好的)是 select 它反对 val():

let $checks = $('body').find('input[type="checkbox"]'),
    value = "B";
    
$checks.each(function() {
  let $this = $(this);
  
  if ($this.val() == value) {
    $this.prop("checked", "checked");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="A">
<input type="checkbox" value="B">
<input type="checkbox" value="C">

你可以通过传递一个比较函数来使用filter

// Reset state
let $checkbox = $('input:checkbox').prop('checked', false);
let valuesToCheck = ['1', '4'];

$checkbox.filter(function() {
  return valuesToCheck.includes(this.value)
}).prop('checked', true); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
<input type="checkbox" value="4">
<input type="checkbox" value="5">

同样的事情,使用箭头函数语法(你不能依赖 'this' 来设置)

$checkbox.filter((i, e) => valuesToCheck.includes(e.value)).prop('checked', true);

对您的原始代码的一些评论:

  • 您不需要 > 0' in yourif` 语句,因为“0”是一个错误值。
  • 您根本不需要 if,因为 for 中的条件永远不会为真,也永远不会 运行.
  • for 中,您正在将 jQuery 集合转换为 jQuery 集合。不需要,直接用checkbox.
  • 最后,您正试图 find 一个包含 input 个元素的集合中的一个 input 元素,因此您将找不到任何东西。你应该使用 checkBox.filter(...).

综合起来:

function reject(el) {
    const $checkBox = $(el).find('input:checkbox');
        for (let j=0;j<tempStore.checks.length;j++) {
            $checkBox.filter((i,e) => e.value == tempStore.checks[j]).prop('checked', true)
        }
    }
}