本文目录导读:
在JavaScript中动态创建文本框和按钮,并在点击按钮时高效地获取文本框的内容,是一个常见的需求,以下是一个简单的示例,展示了如何实现这一功能。
我们需要在HTML中提供一个容器,用于动态插入文本框和按钮。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Textbox and Button</title> </head> <body> <div id="container"></div> <button id="addButton">Add Textbox and Button</button> <script src="script.js"></script> </body> </html>
我们在script.js
文件中编写JavaScript代码,用于动态创建文本框和按钮,并处理按钮点击事件以获取文本框的内容。
document.addEventListener('DOMContentLoaded', (event) => { const container = document.getElementById('container'); const addButton = document.getElementById('addButton'); let textboxCounter = 0; addButton.addEventListener('click', () => { // Create a new textbox const textbox = document.createElement('input'); textbox.type = 'text'; textbox.id =textbox${textboxCounter}
; textbox.placeholder =Enter text ${textboxCounter + 1}
; // Create a new button const getButton = document.createElement('button'); getButton.innerText = 'Get Text'; getButton.dataset.textboxId =textbox${textboxCounter}
; // Store the textbox ID in a data attribute // Add event listener to the new button getButton.addEventListener('click', () => { const textboxId = getButton.dataset.textboxId; const textValue = document.getElementById(textboxId).value; alert(The text in textbox ${textboxCounter + 1} is: ${textValue}
); }); // Append the textbox and button to the container container.appendChild(textbox); container.appendChild(getButton); container.appendChild(document.createElement('br')); // Add a line break for spacing textboxCounter++; }); });
1、HTML 部分:
- 一个div
容器用于放置动态创建的文本框和按钮。
- 一个按钮用于触发创建新的文本框和按钮。
2、JavaScript 部分:
- 使用DOMContentLoaded
事件确保DOM完全加载后再执行脚本。
- 获取容器和添加按钮的引用。
- 使用一个计数器textboxCounter
来确保每个文本框和按钮都有唯一的ID。
- 在点击添加按钮时:
- 创建一个新的文本框,并设置其类型、ID和占位符。
- 创建一个新的按钮,并设置其文本内容,使用data-textboxId
属性存储对应的文本框ID。
- 为新按钮添加点击事件监听器,当按钮被点击时,通过data-textboxId
获取对应的文本框内容,并显示在一个警告框中。
- 将文本框、按钮和一个换行符添加到容器中。
- 递增计数器以准备下一次创建。
这种方法确保了每次添加的新文本框和按钮都能独立工作,并且可以通过简单的数据属性关联来高效地获取文本框的内容。