我正在学习JS以及如何添加数组元素。我希望将表单中提交的信息作为新的数组元素并将其显示在下面。无法使用JS找到实现它的方法。有人可以帮忙吗?到目前为止找到我的代码,这不起作用:
<!DOCTYPE html>
<html>
<body>
<form>
New array element:<br>
<input id="age" type="text" name="firstname" value="">
<br>
<br>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Mango", "Apple"]
var newArray = document.getElementById("age").value;
fruits.push(newArray);
document.getElementById("demo").innerHTML = fruits;
</script>
</body>
</html>
&#13;
谢谢!
答案 0 :(得分:1)
答案 1 :(得分:1)
您需要定义myFunction()
<!DOCTYPE html>
<html>
<body>
<form onsubmit="myFunction()">New array element:
<br>
<input id="age" type="text" name="firstname" value="">
<br>
<br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
<script>
function myFunction() {
var newArray = document.getElementById("age").value;
fruits.push(newArray);
document.getElementById("demo").innerHTML = fruits;
}
var fruits = ["Banana", "Mango", "Apple"];
myFunction(); // initialize demo innerHTML
</script>
</body>
</html>