我如何循环遍历共享一个类的一些 div,并为它们应用唯一的 id?

huangapple go评论99阅读模式
英文:

How can I loop through some divs that share a class and apply a unique id to them?

问题

Sure, here's the translated code part you requested:

  1. 我有一组具有相同类名但没有独立iddiv它们在html中显示的顺序很重要必须保留我需要能够循环遍历由`document.getElementsByClassName(className);`给出的元素列表并为它们每个提供一个形式为`"tile-1" "tile-2"`等的唯一id
  2. 我认为像这样的代码可能有效但很快我意识到这不会起作用
  3. ```js
  4. const getTiles = document.getElementsByClassName(tileClass);
  5. let n = 1;
  6. for (e in getTiles){
  7. let i = "tile-" + n;
  8. e.setAttribute("id", i);
  9. n++;
  10. }

我希望数组中的每个元素都能应用setAttribute,但我错了。

有什么建议吗?

  1. <details>
  2. <summary>英文:</summary>
  3. I have a set of divs that share a class name, but have no individual id. The order in which they show up in html is important and must be preserved. I need to be able to loop through the list of elements given by `document.getElementsByClassName(className);` and give them each a unique id in the form `&quot;tile-1&quot; &quot;tile-2&quot; etc`.
  4. I thought something like this may work but I soon came to realise that this would not work:
  5. ```js
  6. const getTiles = document.getElementsByClassName(tileClass);
  7. let n = 1;
  8. for (e in getTiles){
  9. let i = &quot;tile-&quot; + n;
  10. e.setAttribute(&quot;id&quot;, i);
  11. n++;
  12. }

I was hoping it would be as easy as each element in the array having the setAttribute applied to them but I was wrong.

Any suggestions?

答案1

得分: 1

尝试一下:

  1. let i = 1;
  2. document.querySelectorAll('.post').forEach(el => {
  3. el.id = 'title-' + i;
  4. i++
  5. })
  1. <div class="post">
  2. </div>
  3. <div class="post">
  4. </div>
  5. <div class="post">
  6. </div>
  7. <div class="post">
  8. </div>
英文:

try that

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. let i = 1;
  2. document.querySelectorAll(&#39;.post&#39;).forEach(el =&gt; {
  3. el.id = &#39;title-&#39; + i;
  4. i++
  5. })

<!-- language: lang-html -->

  1. &lt;div class=&quot;post&quot;&gt;
  2. &lt;/div&gt;
  3. &lt;div class=&quot;post&quot;&gt;
  4. &lt;/div&gt;
  5. &lt;div class=&quot;post&quot;&gt;
  6. &lt;/div&gt;
  7. &lt;div class=&quot;post&quot;&gt;
  8. &lt;/div&gt;

<!-- end snippet -->

答案2

得分: 0

如评论中由 @Barmar 指出,我需要在for循环中使用 of 而不是 in。现在按预期运行。

英文:

As pointed out by @Barmar in the comments, I needed to use of instead of in in the for loop. Works as intended now.

huangapple
  • 本文由 发表于 2023年5月11日 00:47:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定