【问题标题】:Is there a way to combine the function body of this forEach funtion?有没有办法组合这个forEach函数的函数体?
【发布时间】:2022-01-07 07:59:58
【问题描述】:

所以我有这个 forEach 函数,它在提交一些数据后替换表格单元格中的文本。我正在根据表格行替换三个不同的表格单元格,并将它们分成三个不同的语句。

像这样:

replaceData.forEach((item, i) => {
  $(`.tableData tbody tr:eq(${item.index})`)
    .children(["td:eq(6)"])
    .text(values[i] === null ? "-" : values[i]);
  $(`.tableData tbody tr:eq(${item.index})`)
    .children("td:eq(7)")
    .text(reason[i]);
  $(`.tableData tbody tr:eq(${item.index})`)
    .children("td:eq(8)")
    .text(notes[i] === null ? "-" : notes[i]);
});

我尝试像这样组合这三个语句,但这不起作用。如果可能的话,有谁知道我如何结合这三个陈述?或者是实现这一点的唯一方法是将它们作为自己的声明?

$(`.tableData tbody tr:eq(${item.index})`)
  .children(["td:eq(6)", "td:eq(7)", "td:eq(8)"])
  .text([
    values[i] === null ? "-" : values[i],
    reason[i],
    notes[i] === null ? "-" : notes[i]
  ]);

【问题讨论】:

  • .each(function (child) { child.text("something" + i) }); 可能会打电话给孩子们吗?
  • .end 是您正在寻找的。 $(foo).children(bar).text('foobar').end().children(baz).text('foobarbaz');api.jquery.com/end
  • 虽然@KevinB 是正确的,并且您可以使用.end 的链接来“返回”...不要。它很难阅读,容易出错,而且性能不如你想的那样好。只需为重复部分设置一个变量var row = $('.tableData tbody tr:eq(' + item.index + ')'),然后取消它。
  • ^^ 绝对同意
  • @KevinB 这无疑是你为什么没有提供它作为答案:)

标签: javascript jquery foreach dry


【解决方案1】:

单独执行它们看起来是正确的做法,将所有内容放在 1 行中并不会为您带来任何好处,并且会损失很多可读性,尤其是在使用大量三元运算时。

但您可以通过创建对行的引用来清理您的代码,而不是每次都重复。

例如。

replaceData.forEach((item, i) => {
  const row = $(`.tableData tbody tr:eq(${item.index})`);                   
  row.children('td:eq(6)').text(values[i] === null ? '-' : values[i])
  row.children('td:eq(7)').text(reason[i]);
  row.children('td:eq(8)').text(notes[i] === null ? '-' : notes[i])
})

如果你有很多列,你甚至可以创建一个简单的内联函数来让事情变得更容易理解。

例如。

replaceData.forEach((item, i) => {
  const row = $(`.tableData tbody tr:eq(${item.index})`);                   
  const R = c => row.children(`td:eq(${c})`);
  R(6).text(values[i] === null ? '-' : values[i]);
  R(7).text(reason[i]);
  R(8).text(notes[i] === null ? '-' : notes[i]);
})

【讨论】:

  • 好的,感谢您的建议!
猜你喜欢
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 2019-09-10
  • 2014-12-11
  • 2019-10-10
  • 1970-01-01
  • 2019-02-26
相关资源
最近更新 更多