JavaScript - 清除数组后在数组上推送值会保留旧值

时间:2014-02-03 17:44:10

标签: javascript prototype

我正在使用JavaScript(原型和ajax),PHP和MySQL在文本字段和下拉列表中显示数据库中的某些值,但我遇到了JavaScript问题。

每次用户点击列表中的选项时,值都应更新。这些值被推入一个数组中,但即使在清除它或将其长度设置为0之后,这些值也会被推到数组之前的结尾。

第一次一切正常,但在此之后数组不断变大,它会在下拉列表中添加越来越多的值。这是代码:

function artSelect(art){
//perform an Ajax request
var artRequest = new XMLHttpRequest();

//If the output is returned successfully, add it in the document
artRequest.onreadystatechange = function() {
    if (artRequest.readyState==4) {
        //Get the text
        var text = artRequest.responseText;
        //Create an array
        var x = new Array();
        //Create a variable for storing the position of the last semicolon (the values are seperated by semicolons)
        var lastSemCol = 0;
        //Split the text by scanning for semicolons and put them in an array
        for (var i=0; i<text.length; i++) {
            //If the current char is ";"
            if (text[i] === ";") {
                //Create a substring of the chars between the last ; and current ;
                var value = text.substr(lastSemCol + 1, i-lastSemCol-1);
                //Add the value to the array
                Array.prototype.push(value);                
                lastSemCol = i;
            }
        }
        //Set the values in the document
        $("beschrijving").value = x[1];
        $("kleur").value = x[2];
        $("voorraad").value = x[3];
        $("prijs").value = x[4];
        $("srtc").value = x[5];
        //Set the departments
        for (var i=6; i < Array.prototype.size(x); i++) {
            var option = document.createElement("option");
            option.text = x[i];
            $("afd").add(option);
        }
        //Clear the array (no effect)
        x.clear();
        x.length = 0;
        x = new Array();
    }
};

artRequest.open("GET", "server.php?mode=getArtikel&artikel=" + selected.value.substr(0,7), true);
artRequest.send(null);
}

0 个答案:

没有答案