首页 > 解决方案 > 如何获取表 TR 上的所有输入值(按 ID)

问题描述

你好吗?

如何获取表中一个 TR 内的所有输入值?我会找到示例,而不是针对特定行(带有 ID)我有这个表:

<table>
   <tr id="a">
      <td><input id="a_01" value="the value of a_01"></td>
      <td><input id="a_02" value="the value of a_02"></td>
   </tr>
   <tr id="b">
      <td><input id="b_01" value="the value of b_01"></td>
      <td><input id="b_02" value="the value of b_02"></td>
   </tr>
</table>

例如:我正在尝试获取 id="b" 的 tr 的所有值输入。

非常感谢您的帮助!

标签: javascriptjqueryinputfrontend

解决方案


您可以使用选择器来定位元素。为此,您不需要 jQuery,因为您可以使用querySelectorandquerySelectorAll函数:

document.querySelector('button').addEventListener('click', function(){
  // Radio input value
  var value = document.querySelector('input[name="idvalue"]:checked').value;

  // Here's the selector for the input elements
  var elements = document.querySelectorAll('#' + value + ' input');
  
  // You can iterate the result and use the element values
  elements.forEach(e => {console.log(e.id + ': ' + e.value);});
});
<table>
   <tr id="a">
      <td><input id="a_01" value="the value of a_01"></td>
      <td><input id="a_02" value="the value of a_02"></td>
   </tr>
   <tr id="b">
      <td><input id="b_01" value="the value of b_01"></td>
      <td><input id="b_02" value="the value of b_02"></td>
   </tr>
</table>
<div>
  <input type="radio" name="idvalue" id="radioa" value="a" checked /><label for="radioa">Show values for #a</label>
  <input type="radio" name="idvalue" id="radiob" value="b" /><label for="radiob">Show values for #b</label>
</div>
<button>Show Values of selected #id</button>

如果您真的 不需要中执行此操作,则可以使用相同的选择器来定位元素:$("#b input").

我建议您进一步阅读这是 MDN 链接


推荐阅读