0

我正在学习 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>

谢谢!

4

2 回答 2

1

您正在单击按钮调用,但inmyFunction()没有函数声明myFunction()<scripts>

   <!DOCTYPE html>
<html>
<body>


New array element:<br>
<input id="age" type="text" name="firstname" value="">
<br>
<br>
<input type="button" value="Submit" onclick="myFunction()">


<p id="demo"></p>

<script>
    var fruits = ["Banana", "Mango", "Apple"];
function myFunction(){
var newArray = document.getElementById("age").value;
fruits.push(newArray);
document.getElementById("age").value = "";
document.getElementById("demo").innerHTML = fruits;
 }
</script>

</body>
</html>

编辑

将数组fruits设为全局,即 var fruits = ["Banana", "Mango", "Apple"];根据 OP 的要求移到函数之外。

于 2015-07-12T16:16:37.307 回答
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>
于 2015-07-12T16:18:19.730 回答