我有两个输入框,我正在尝试比较它们,以便查看它们是否有共同的元素。但是出于某种原因,它无法正常工作。我的代码:
HTML:
Personal Address line 1: <input type = "text" id = "persAdd1" />
Address Line 1: <input type = "text" id = "addLine1" />
<input type = "submit" value = "Continue" onclick = "vali()" />
JavaScript的:
function vali() {
var add1Str = document.getElementById('persAdd1').value;
var add2Str = document.getElementById('addLine1').value;
var arr1 = add1Str.split(" ");
var arr2 = add2Str.split(" ");
var arr3 = [];
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] === arr2[j]) {
arr3.push( arr1[i] );
if(arr3 !== ""){
alert("error");
}
}
}
}
}
有什么想法吗?
答案 0 :(得分:0)
以下内容适合您。
function vali() {
var add1Str = document.getElementById('persAdd1').value;
var add2Str = document.getElementById('addLine1').value;
var arr1 = add1Str.split(" ");
var arr2 = add2Str.split(" ");
var arr3 = [];
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] === arr2[j]) {
arr3.push(arr1[i]);
//console.log(arr3);
}
}
}
if (arr3.length > 0) { //check if the array 3 has any items, if yes alert error.
alert("error");
}
}