【问题标题】:How to get all input values on a table TR (by ID)如何获取表 TR 上的所有输入值(按 ID)
【发布时间】:2019-09-02 15:30:36
【问题描述】:

你好吗?

如何获取表中一个 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 的所有值输入。

非常感谢您的帮助!

【问题讨论】:

  • 这是其中一个问题,老实说,您最好阅读介绍性 jquery 而不是在这里提问。

标签: javascript jquery input frontend


【解决方案1】:

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

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")

我建议您进一步阅读Here's the MDN link.

【讨论】:

  • 感谢@Niche 的帮助。我是后端开发人员,我在前端遇到了一些麻烦:( jajaja。我可以在 ('#b input') 中传递一个 var,比如 ('#'+id`+'input')?我是出现一些错误(无法在“文档”上执行“querySelector”:“#6640e122-2d43-4bce-b1f4-96bb8b68476a”不是有效的选择器)......
  • 是的,您可以为选择器使用动态值,因为 querySelectorquerySelectorAll 需要一个字符串参数作为选择器值。我更新了我的示例以包含动态选择器。
猜你喜欢
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-31
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
相关资源
最近更新 更多