簡體   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