我正在尝试使用JavaScript中的用户输入创建一个数组,并在数字附加到数组时显示最新的数组。这些数字没有打印出来。 请帮助。
HTML部分:
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<form id = "arrays" method = "" onsubmit="arrAppend(document.getElementById('num').value);">
<input type ="submit" value="Append" />
</form>
JavaScript部分:
<script>
var myarr = [];
function arrAppend(num) {
myarr.push(+num);
text = "";
for (var x = 0; x< myarr.length; x++) {
text += myarr[x];
}
console.log(text);
}
</script>
答案 0 :(得分:0)
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<input type ="submit" value="Append" onclick="arrAppend(document.getElementById('num').value);"/>
为什么需要表格?你在服务器上提交的东西?提交表单时,它也会清除全局数组。
答案 1 :(得分:0)
这是有效的:
HTML:
<input type = "text"
id = "addNumber" />
<input type = "button"
id = "addToArray"
value = "Append"
onclick = "arrAppend();" />
JavaScript:
function arrAppend() {
myarr[x] = document.getElementById('addNumber').value;
alert("Element : "+myarr[x]+" is added at index "+x);
x++;
document.getElementById('addNumber').value = "";