如何显示以前的用户输入以及新输入

时间:2013-10-22 08:27:41

标签: javascript html

我是Html的新手,我正在尝试创建一个脚本来向用户显示用户输入。每当我输入一个新输入时,新用户输入将覆盖前一个输入。但我需要显示所有用户输入?如何使用Javascript。

我的代码

<html><head></head><body>

<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />

<div id="display2letter"></div>
<div id="display3letter"></div>
<div id="display4letter"></div>

<script type="text/javascript">
var titleInput  = document.getElementById("title");
var display2letter  = document.getElementById("display2letter");
var display3letter  = document.getElementById("display3letter");
var display4letter  = document.getElementById("display4letter");

function clearAndShow () {
    // Split input box value by comma
    titles = titleInput.value.split(",");

    // Reset display divs
    display2letter.innerHTML = "";
    display3letter.innerHTML = "";
    display4letter.innerHTML = "";

    // Cache length so it's not recalculated on each iteration.
    var len = titles.length;
    var twoletter = [];
    var threeletter = [];
    var fourletter =[];
    for (i = 0; i < len; i++) {
        // Check for a-z, A-Z, 
        if (!titles[i].match(/^[a-zA-Z]/)) {
       throw error("Please use only alphabet letters");

        }

        // Dump into storage arrays.
        if(titles[i].length == 2) {
                twoletter.push(titles[i]);
        }
        else if(titles[i].length == 3){
            threeletter.push(titles[i]);
        }
        else if(titles[i].length == 4){ 
                    fourletter.push(titles[i]);
        }
    }

    display2letter.innerHTML += " 2 letters: " + twoletter.join(", ") + "<br/>";
    display3letter.innerHTML += " 3 letters: " + threeletter.join(", ") + "<br/>";
    display4letter.innerHTML += " 4 letters: " + fourletter.join(", ") + "<br/>";
}
</script>
</body>

</html>

1 个答案:

答案 0 :(得分:2)

尝试声明这些变量 -

 var twoletter = [];
 var threeletter = [];
 var fourletter =[];
clearAndShow ()函数之前的

,即

<script type="text/javascript">
var titleInput  = document.getElementById("title");
var display2letter  = document.getElementById("display2letter");
var display3letter  = document.getElementById("display3letter");
var display4letter  = document.getElementById("display4letter");
var twoletter = [];
var threeletter = [];
var fourletter =[];

function clearAndShow () {