如何在HTML中获取所有的input中的值
时间: 2023-08-12 13:08:11 浏览: 47
要在 HTML 中获取所有输入框(input)的值,你可以使用 JavaScript 来访问每个输入框元素并获取其值。以下是一个示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>获取所有输入框的值</title>
</head>
<body>
<input type="text" id="input1" value="Value 1">
<input type="text" id="input2" value="Value 2">
<input type="text" id="input3" value="Value 3">
<button onclick="getAllInputValues()">获取所有输入框的值</button>
<script>
function getAllInputValues() {
const inputs = document.querySelectorAll('input');
const inputValues = [];
inputs.forEach(function(input) {
inputValues.push(input.value);
});
console.log(inputValues);
}
</script>
</body>
</html>
```
在上述示例中,我们使用 `document.querySelectorAll('input')` 来获取所有的输入框元素,并将其存储在 `inputs` 变量中。然后,使用 `forEach` 方法遍历每个输入框,并将其值通过 `input.value` 获取并添加到 `inputValues` 数组中。最后,通过 `console.log` 将所有的输入框值输出到控制台。
当你点击 "获取所有输入框的值" 按钮时,控制台将打印出所有输入框的值。
请注意,`querySelectorAll` 返回的是一个 NodeList 对象,你可以使用 `forEach` 方法或其他方法来遍历并操作其中的元素。