使用Javascript动态数组输入

Dynamically array input with Javascript

本文关键字:输入 数组 动态 Javascript 使用      更新时间:2023-09-26

我想输入数组的数量,输出将跟随它的数量。例如:如果我在输入文本中输入"7"。结果将显示多达7。这是我的代码:

<html>
<head>
<title>JavaScript - Input Text Field</title>
</head>
<body>
<form name="test">
<H2>Enter something into the field and press the button. <br></H2>
<P>Amount of Tables: <input type="TEXT" name="amount"><BR><BR>
<input type="Button" Value="Show and Clear Input" onClick="myFunction()"></P>
</form>
<p id="demo"></p>
<script>
function myFunction() {
     var text = "";
     var i;
     var j = document.getElementsByName("amount");
     for (i = 0; i < j.length; i++) {
           text += "The number is " + i + "<br>";
     }
     document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

您的JavaScript 有问题

参见代码:

function myFunction() {
     var text = "";
     var i;
     var j = document.getElementsByName("amount")[0];
     for (i = 0; i < j.value; i++) {
           text += "The number is " + j.value + "<br>";
     }
     document.getElementById("demo").innerHTML = text;
}

.getElementsByName返回一个元素数组,因此需要指定元素的索引,以便访问其属性。

Fiddle here