我需要结合一些过滤条件,包括静态和动态条件(数量未知的动态条件,范围从1到10甚至更大)。如何才能做到这一点?我总是得到错误的结果,我有一种感觉,for循环一次只在一个动态条件下运行。谢谢你的想法!
const Count = 3;
for (let i = 0; i < Count; i++) {
$("#static").val == "10" && $(".sample:eq(" + i + ")").val() == "1");
}
应导致:
$("#static").val() == "10" &&
$(".sample:eq(0)").val() == "1") &&
$(".sample:eq(1)").val() == "1") &&
$(".sample:eq(2)").val() == "1")
答案 0 :(得分:1)
如果您想满足您的条件,则:
#static
元素的值为'10'
和.sample
元素的值均为'1'
,...您可以使用以下条件:
// Get first 3 `.sample` elements, and see if their values are '1'
const $matchingSamples = $('.sample').filter(function(i) {
return i <= 2 && this.value === '1';
});
// Combine all your conditions
const condition = $('#static').val() === '10' && $matchingSamples.length === 3;
condition
变量将等效于:
$('#static').val() === '10' &&
$('.sample:eq(0)').val() === '1') &&
$('.sample:eq(1)').val() === '1') &&
$('.sample:eq(2)').val() === '1')
当然,您可以在ES6中重写上面的逻辑以完全不使用jQuery:
const samples = document.querySelectorAll('.sample');
const matchingSamples = Array.from(samples).filter((sample, i) => {
return i <= 2 && sample.value === '1';
})
const condition = document.getElementById('static').value === '10' && matchingSamples.length === 3;
请参见下面的概念验证:
const numberOfSamplesToCheck = 3;
function checkValues() {
const $matchingSamples = $('.sample').filter(function(i) {
return i <= numberOfSamplesToCheck - 1 && this.value === '1';
});
const condition = $('#static').val() === '10' && $matchingSamples.length === numberOfSamplesToCheck;
console.log(condition);
}
checkValues();
$(':input').on('change', checkValues);
input {
border: 1px solid #000;
width: 75px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="static" value="10" type="number" />
<input class="sample" value="1" type="number" />
<input class="sample" value="1" type="number" />
<input class="sample" value="1" type="number" />