首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取HTML表中几个元素的Id和值

获取HTML表中几个元素的Id和值
EN

Stack Overflow用户
提问于 2018-06-20 01:38:31
回答 1查看 42关注 0票数 0

基本上我需要将文本框的id和value保存在一个表中,我知道我可以通过以下方式访问它们:

代码语言:javascript
复制
var value = document.getElementById("idOne").value;
var id = document.getElementById("idOne").id;

但问题是,我知道本例中的id,我不应该知道,我需要一些方法来获取不同文本框的id,并将它们保存在一个数组中。

我以下面的表格为例:

我打算做的是将值保存在两个变量中,如下所示

代码语言:javascript
复制
id = ["idOne", "idTwo", "idTree"..... 

(其中的id是来自textBoxes的id)

代码语言:javascript
复制
value = ["value1" , "value2" , "value3".....

是的,值在文本框中:(

代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

发布于 2018-06-20 01:46:31

我使用document.querySelectorAll获取输入并将它们存储在一个对象中。

代码语言:javascript
复制
// 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);
代码语言:javascript
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50934080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档