javascript 中的 getelementbyid 列表
getelementbyid list in javascript
我正在尝试创建一个循环,将来自输入的值放入数组中。
关键是我有 81 个输入,它们的 ID 是“cells-[x]
”。
我尝试做的是
<script type="text/javascript">
var test = [];
for(i=0;i<80;i++){
test[i]=(document.getElementById('cell-[i]').value);
}
</script>
但它不起作用。
B.T.W,我可能在for循环本身犯了错误,但这不是我的重点(我只是初学者)。
两件事:
1. 你的 'cell-[i]'
全部在一个字符串中,所以每次它认为你正在取值:'cell-[i]'
。将 getElementById
中的参数替换为:
('cell-[' + i + ']').
2.尝试:
test.push(document.getElementById('cell-[' + i + ']').value)
应该这样做。
您可以对表单使用 addEventListener
并调用自定义函数 getValues()
,这将获取所有输入的值。您可以使用 querySelectorAll()
to collect all the inputs once regardless of what their id
is, and then loop over them using forEach
and use .push()
将值添加到我们将用于收集输入值的数组。
查看下面的演示,尝试向输入添加值并点击提交按钮
//get all the inputs
var inputs = document.querySelectorAll("input");
// valArray used to collect the values of input
var valArray = [];
//function to get the values of the form inputs
function getValues() {
//loop the aray using foreach
inputs.forEach(function(input) {
//use array.push() to add the values to the custom array of input values
valArray.push(input.value);
});
}
//add submit event listner for the form
document.querySelector("#my-form").addEventListener("submit", function(e) {
e.preventDefault(); //stop form from submitting
getValues();
console.log(valArray);
});
<form name="my-form" id="my-form">
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input type="submit">
</form>
我正在尝试创建一个循环,将来自输入的值放入数组中。
关键是我有 81 个输入,它们的 ID 是“cells-[x]
”。
我尝试做的是
<script type="text/javascript">
var test = [];
for(i=0;i<80;i++){
test[i]=(document.getElementById('cell-[i]').value);
}
</script>
但它不起作用。
B.T.W,我可能在for循环本身犯了错误,但这不是我的重点(我只是初学者)。
两件事:
1. 你的 'cell-[i]'
全部在一个字符串中,所以每次它认为你正在取值:'cell-[i]'
。将 getElementById
中的参数替换为:
('cell-[' + i + ']').
2.尝试:
test.push(document.getElementById('cell-[' + i + ']').value)
应该这样做。
您可以对表单使用 addEventListener
并调用自定义函数 getValues()
,这将获取所有输入的值。您可以使用 querySelectorAll()
to collect all the inputs once regardless of what their id
is, and then loop over them using forEach
and use .push()
将值添加到我们将用于收集输入值的数组。
查看下面的演示,尝试向输入添加值并点击提交按钮
//get all the inputs
var inputs = document.querySelectorAll("input");
// valArray used to collect the values of input
var valArray = [];
//function to get the values of the form inputs
function getValues() {
//loop the aray using foreach
inputs.forEach(function(input) {
//use array.push() to add the values to the custom array of input values
valArray.push(input.value);
});
}
//add submit event listner for the form
document.querySelector("#my-form").addEventListener("submit", function(e) {
e.preventDefault(); //stop form from submitting
getValues();
console.log(valArray);
});
<form name="my-form" id="my-form">
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input type="submit">
</form>