基本上我需要将文本框的id和value保存在一个表中,我知道我可以通过以下方式访问它们:
var value = document.getElementById("idOne").value;
var id = document.getElementById("idOne").id;
但问题是,我知道本例中的id,我不应该知道,我需要一些方法来获取不同文本框的id,并将它们保存在一个数组中。
我以下面的表格为例:
我打算做的是将值保存在两个变量中,如下所示
id = ["idOne", "idTwo", "idTree".....
(其中的id是来自textBoxes的id)
value = ["value1" , "value2" , "value3".....
是的,值在文本框中:(
<table style="width:10%">
<tr>
<th>Number</th>
<th>Value</th>
</tr>
<tr>
<td>One</td>
<td><input type="text" id="idOne" name="idOne" value="value1" size="" maxlength="2000" /></td>
</tr>
<tr>
<td>Two</td>
<td><input type="text" id="idTwo" name="idTwo" value="value2" size="" maxlength="2000" /></td>
</tr>
<tr>
<td>Tree</td>
<td><input type="text" id="idTree" name="idTree" value="value3" size="" maxlength="2000" /></td>
</tr>
<tr>
<td>Four</td>
<td><input type="text" id="idFour" name="idFour" value="value4" size="" maxlength="2000" /></td>
</tr>
<table>
发布于 2018-06-20 01:46:31
我使用document.querySelectorAll获取输入并将它们存储在一个对象中。
// Plain JS (ES6 is not compatible with IE without Babel or polyfills)
var inputs = document.querySelectorAll("table input"), obj = {};
for (var i=0;i<inputs.length;i++) {
obj[inputs[i].id]=inputs[i].value;
}
console.log(obj);
// ES6 version
let obj1 = {};
[...document.querySelectorAll('table input')] // destructures collection into array
.forEach(input => obj1[input.id] = input.value);
console.log(obj1);
<table style="width:10%">
<tr>
<th>Number</th>
<th>Value</th>
</tr>
<tr>
<td>One</td>
<td><input type="text" id="idOne" name="idOne" value="value1" size="" maxlength="2000" /></td>
</tr>
<tr>
<td>Two</td>
<td><input type="text" id="idTwo" name="idTwo" value="value2" size="" maxlength="2000" /></td>
</tr>
<tr>
<td>Tree</td>
<td><input type="text" id="idTree" name="idTree" value="value3" size="" maxlength="2000" /></td>
</tr>
<tr>
<td>Four</td>
<td><input type="text" id="idFour" name="idFour" value="value4" size="" maxlength="2000" /></td>
</tr>
<table>
https://stackoverflow.com/questions/50934080
复制相似问题