使用按钮清空或重置整个数组

时间:2012-09-27 23:20:40

标签: javascript

这是我的脚本可能更容易解释,如果你可以看到它,我想用一个按钮重置数组

 <body> 
  <script type="text/javascript"> 
   var number = []; 

   function myFunction() 
   { 
     var x = document.getElementById("box"); 
     number.push(document.getElementById("input").value); 
     x.innerHTML = number.join('<br/>');  
   } 


  </script> 
 <form> 
  <input id="input" type=text> 
   <input type=button onclick="myFunction()" value="Add to list"/>  
  </form>

 <div id="box" style="border:1px solid black;width:150px;height:150px;overflow:scroll">  
  </div> 
<form>
<input type=button onclick="number.splice(0)" value="Reset" />
</form>
</body> 
</html>

2 个答案:

答案 0 :(得分:1)

是。从函数中调用它。

编辑:拼接有IE问题。使用array.length = 0代替

<body> 
    <script type="text/javascript"> 
        var number = []; 

        function myFunction() { 
            var x = document.getElementById("box"); 
            number.push(document.getElementById("input").value); 
            x.innerHTML = number.join('<br/>');  
        } 

        function myReset() {
            //number.splice(0);
            number.length = 0;
            var x = document.getElementById("box"); 
            x.innerHTML = "";
            x.innerHTML = number.join('<br/>');  
        }
    </script> 

    <form> 
        <input id="input" type=text> 
        <input type=button onclick="myFunction()" value="Add to list"/>  
    </form>

    <div id="box" style="border:1px solid black;width:150px;height:150px;overflow:scroll">  
    </div> 
    <form>
        <input type=button onclick="myReset()" value="Reset" />
    </form>
</body> 

答案 1 :(得分:0)

尽管丑陋,但onclick="number.splice(0)"仍有效:http://jsfiddle.net/39KZ9/20/