0

我有两个输入框,我正在尝试比较它们,以查看它们是否有共同的元素。但是,由于某种原因,它不起作用。我的代码:

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");
                }
            }
        }
    }
}

jsFiddle

有任何想法吗?

4

1 回答 1

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");
    }
}

演示

于 2013-09-03T15:11:37.280 回答