我的 HTML 文档中有四个文本框,分别是 textbox1、textbox2、textbox3、textbox4,单击按钮单击 btn1 我想确保在所有四个文本框中输入的所有值都是不同且唯一的。为此,我使用了 if 条件。
$("#btn1").on("click", function(){
if($("#textbox1").val() === $("#textbox2").val() ||
$("#textbox1").val() === $("#textbox3").val() ||
$("#textbox1").val() === $("#textbox4").val() ||
$("#textbox2").val() === $("#textbox3").val() ||
$("#textbox2").val() === $("#textbox4").val() ||
$("#textbox3").val() === $("#textbox4").val() )
{ alert("Values are not unique please check them."); }
});
还有比这更短的方法吗?
最佳答案
你可以用数组做一个集合。该集合会删除重复项,因此如果长度不匹配,则存在重复项。
function checkIfArrayIsUnique(myArray) {
return myArray.length === new Set(myArray).size;
}
$("button").on("click", function () {
var vals = $(".tb").map( function () { return this.value }).get()
console.log(checkIfArrayIsUnique(vals))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" class="tb" />
<input type="text" class="tb" />
<input type="text" class="tb" />
<input type="text" class="tb" />
<button type="button">Check</button>
如果您正在寻找不区分大小写的唯一文本,您可能需要“标准化”这些值。示例“aaa”与“AAA”....
关于javascript - 使用 If 语句检查值的有效方法未在 Javascript 或 JQuery 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60958197/