【问题标题】:Select element in jquery collection by value using variable使用变量按值选择jquery集合中的元素
【发布时间】:2019-11-09 19:58:51
【问题描述】:
我正在使用 jQuery 并且有一个包含来自页面的输入的集合(对象?)。我有一个变量保存循环的每次迭代的 value 属性。我想找到与我的变量匹配的值的输入,以便我可以选中复选框。
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;
}
}
}
我已经在网上搜索了几个小时,但找不到正确的语法。有人可以帮忙吗?
【问题讨论】:
标签:
javascript
jquery
jquery-selectors
【解决方案1】:
如果该值是在 DOM 中设置的,您可以尝试通过 attribute 和 [value=""] 选择器选择它:
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 一个已填充的元素列表,而不是find。
另一种解决方案(不是最好的)是针对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">
【解决方案2】:
您可以通过传递比较函数来使用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);
关于您的原始代码的一些 cmets:
- 您不需要
> 0' in yourif` 语句,因为“0”是一个虚假值。
- 您根本不需要
if,因为for 中的条件永远不会为真,也永远不会运行。
- 在
for 中,您正在将一个jQuery 集合转换为一个jQuery 集合。没必要,用checkbox就行了。
- 最后,您尝试在由
input 元素组成的集合中添加find 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)
}
}
}