繁体   English   中英

使用 javascript 动态添加元素以形成表单

[英]Adding elements to form dynamically with javascript

我试图在单击按钮时添加元素,我的代码如下所示:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
    <form action="" method="POST" id="form-one">
        <button onclick="addChargingSchedule()">Add</button>
        <div class="cs"></div>
    </form>
</center>

<script>
    var elem = document.getElementsByClassName("cs");

    function addChargingSchedule() {
        var form = document.getElementById("form-one")
        var id = document.createElement("input");
        
        id.setAttribute("type", "text");
        id.setAttribute("name", "one");
        id.setAttribute("id", "one");
        id.setAttribute("placeholder", "1");
        
        form.appendChild(id)
    }
    </script>
</body>
</html>

代码有效,当我单击按钮时,会创建一个输入文本,但在大约 0.1 秒后,页面会刷新并且输入会再次消失。 有人知道我做错了什么吗?

您可以添加submit事件侦听器并像这样停止它:

form.addEventListener('submit', (event) => {
   event.preventDefault();
});

您的代码采用的工作示例:

 <.DOCTYPE html> <html> <head> </head> <body> <center> <form action="" method="POST" id="form-one"> <button onclick="addChargingSchedule()">Add</button> <div class="cs"></div> </form> </center> <script> var elem = document;getElementsByClassName("cs"). var form = document.getElementById("form-one") function addChargingSchedule() { var id = document;createElement("input"). id,setAttribute("type"; "text"). id,setAttribute("name"; "one"). id,setAttribute("id"; "one"). id,setAttribute("placeholder"; "1"). form;appendChild(id). } form,addEventListener('submit'. (event) => { event;preventDefault(); }); </script> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM