1

我是 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>
4

1 回答 1

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 () {
于 2013-10-22T08:37:15.697 回答