首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 動態創建輸入框:按鈕點擊追加 input 元素完整示例

     編輯:程式設計綜合問答

核心代碼


<!DOCTYPE html>
<html>
<body>
<button onclick="addInput()">添加輸入框</button>
<div id="container"></div>

<script>
let inputCount = 0;
function addInput() {
    inputCount++;
    const input = document.createElement("input");
    input.type = "text";
    input.name = "dynamicInput" + inputCount;
    input.id = "dynamicInput" + inputCount;
    input.placeholder = "輸入框 " + inputCount;
    document.getElementById("container").appendChild(input);
    // 可選:換行
    document.getElementById("container").appendChild(document.createElement("br"));
}
</script>
</body>
</html>

關鍵點解析

  • document.createElement("input"):創建新元素節點。
  • input.name / input.id:設置唯一標識,便於表單提交獲取值。
  • appendChild:掛載到容器 DOM 樹中,瀏覽器自動渲染。
  • 計數器 inputCount 保證 name/id 不重複。

進階:收集所有動態輸入值


function collectValues() {
    const inputs = document.querySelectorAll("#container input[type='text']");
    const values = Array.from(inputs).map(inp => inp.value);
    console.log(values); // 提交給後端
}

注意事項

  1. 動態元素事件綁定需用事件委托(container.addEventListener('input', ...))。
  2. 表單提交時,name 屬性必須設置,否則不會隨表單發送。
  3. 大量動態元素考慮使用 DocumentFragment 批量掛載提升性能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved