【问题标题】:Push input fields from selected table row into array to loop through将选定表格行中的输入字段推入数组以循环
【发布时间】:2020-09-12 21:12:26
【问题描述】:

我想将我的表(特定行)中的一些输入字段添加到数组中。稍后我想循环遍历这个数组。

我是这样做的:

let selectedTr = [];
let arr = [];

$('td input:checked').each(function() {
    selectedTr.push($(this).closest('tr'));
});

selectedTr.forEach((tr) => {
  td = tr.find('td:not(:first-child) input');

  td.each(function() {
    arr.push($(this));
  });
});

// Doesn't work if I define arr like above (error: arr.each is not a function, if I use `arr = $('form input')` it works perfectly for example)
arr.each(function() {
    ...
});

这是一个关于 jsfiddle 的简短演示:https://jsfiddle.net/a4fpqynx/ PS:在jsfiddle中我得到:如果我使用console.log(),则无法克隆错误对象。

arr 显示类似 (S on every line):

0 S [<input type="text">] (1)
1 S [<input type="text">] (1)
...

但我需要(只需要一个 S)

S
0 [<input type="text">]
1 [<input type="text">]
...

所以我可以使用arr.each。 PS:arr.each(function() {}) 位于另一个函数中,该函数从多个文件中调用以检查输入字段。我将其用于登录、表格和其他表单。 我怎样才能做到这一点?

【问题讨论】:

    标签: javascript jquery arrays loops foreach


    【解决方案1】:
      const rowList = [...document.querySelectorAll('tr')]
      const inputList = rowList.filter(row => row.firstElementChild.firstElementChild.checked).map(row => {
          return [...row.querySelectorAll('input')]
      })
      console.log(inputList)
    

    【讨论】:

    • 感谢您的回答。但我需要检查表行中的输入字段:)。不是复选框。
    • Gotcha 将修复
    • @Lupin 变了,让我知道情况如何。
    • 我试试看:)。
    猜你喜欢
    • 2020-09-11
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    相关资源
    最近更新 更多