【问题标题】:increse number value each time its looped每次循环时增加数值
【发布时间】:2022-12-08 23:02:43
【问题描述】:

我想我在路上搞砸了,让事情变得比实际情况更复杂,所以就这样......所以如果有人暗示我应该怎么做,我会很高兴。

起初我有一个数组

const cars = ["Saab", "Volvo", "BMW"];

我的问题是我想在每个数组值中添加一个标记,但我发现这并不容易。所以我确实喜欢这样:

const cool = '<a href="coolLink?id=1">Cool link</a>';

这是我的循环:

  cars.forEach(function(e, index){
    $('.row')[index].append(e);
    $('.row')[index].insertAdjacentHTML('beforeend' , cool);
  });

所以我能够让它工作,我的酷链接按预期工作。但是,正如您在我的 href 中看到的那样,我目前在那里有一个 ID。所有的汽车都应该有一个唯一的 ID。无论如何,每次它循环时我都可以 +1 id 吗?或者我可以通过其他方式实现这一目标吗?像这样不起作用:

const cars = ["Saab<a href="coolLink?id=1">Cool link</a>", "Volvo<a href="coolLink?id=2">Cool link</a>", "BMW<a href="coolLink?id=3">Cool link</a>"];

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:

    如果您在“循环”中定义cool,那么您可以在定义它时使用index,例如:

    cars.forEach(function(e, index){
      const cool = `<a href="coolLink?id=${index + 1}">Cool link</a>`;
      $('.row')[index].append(e);
      $('.row')[index].insertAdjacentHTML('beforeend' , cool);
    });
    

    【讨论】:

    • ahhhhhh,这比我想象的要简单。非常感谢您的回答!
    • @Jacktheman - 请注意,此解决方案使用的是Template Literals。它需要反引号,并且在这种情况下 $ 不是 jQuery。 +1
    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2017-02-09
    相关资源
    最近更新 更多