如何设置一个条件,如果值都为真,我的函数继续?



我想在所有.numberstrue时启动一个新函数。如果有人false我想在他发现所有错误后停止该功能。.numbers是我表中的一列。我想检查它们是否正确。我不知道如何实现这一点。你能帮我吗?

$("#clickit").click(function() {
$(".numbers").filter(function() {
if ($.isNumeric($(this).text()) === false) {
$(this).css("background-color", "red");
return false;
} else {
alert("out1");
}
});
});

有很多方法可以做到这一点,这里有一个选项:

  • 查找所有无效数字并给它们一个类
  • 检查该类是否有任何元素

这可以组合,但为简单起见,将它们视为两个不同的检查:

$(".numbers").each(function() {
$(this).toggleClass("notvalid", !$.isNumeric($(this).text()));
});
if ($(".numbers.notvalid").length === 0)
// ok to continue

演示片段:

$(".numbers").each(function() {
$(this).toggleClass("notvalid", !$.isNumeric($(this).text()));
});
// Example usage
if ($(".numbers.notvalid").length === 0)
$("#out").text("all pass");
else 
$("#out").text("not all passed");
.notvalid { background-color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr><td>Line1</td><td class='numbers'>123</td></tr>
<tr><td>Line2</td><td class='numbers'>abc</td></tr>
<tr><td>Line3</td><td class='numbers'>456</td></tr>
<tr><td>Line4</td><td class='numbers'>789</td></tr>
<table>
<hr/>
<div id="out"></div>


要更新您的尝试,可以使用.filter通过返回 true(保留在列表中(/false (从列表中删除(来返回过滤列表。 由于您不想检查有多少要比较,因此您可以返回失败的数量(类似于上面(,给出:

$("#clickit").click(function() {
if ($(".numbers").filter(function() {
if ($.isNumeric($(this).text()) === false) {
$(this).css("background-color", "red");
return true;
} else {
// reset the "red" ones - this is easier with add/remove class
$(this).css("background-color", "white");
return false;
}
})).length === 0) {
// none have an error, ok to continue
}
});

您可以为此设置一个标志:

$("#clickit").click(function() {
let flag = 0;
$(".numbers").filter(function() {
if ($.isNumeric($(this).text()) === false) {
$(this).css("background-color", "red");
flag++;
} else {
$(this).css("background-color", ""); // Remove the css as well.
}
});
if (flag) {
//error handling.
} else {
//continue your logic
}
});

还有另一种解决方案,您可以count无效text的数量,如果它等于零,则意味着您的所有texttrue

$("#clickit").click(function() {
invalid = 0;
$(".numbers").filter(function() {
if (!$.isNumeric($(this).text())) {
invalid++;
$(this).css("background-color", "red");
return false;
}
});
if (invalid === 0) {
alert('all set!')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<td class="numbers">2</td>
<td class="numbers">1</td>
<td class="numbers">1</td>
<td class="numbers">3</td>
</tr>
</tbody>
</table>
<button id="clickit">Check</button>

最新更新