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

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

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:

我有一组具有相同类名但没有独立id的div它们在html中显示的顺序很重要必须保留我需要能够循环遍历由`document.getElementsByClassName(className);`给出的元素列表并为它们每个提供一个形式为`"tile-1" "tile-2"`等的唯一id

我认为像这样的代码可能有效但很快我意识到这不会起作用

```js 
const getTiles = document.getElementsByClassName(tileClass);
let n = 1;
for (e in getTiles){
  let i = "tile-" + n;  
  e.setAttribute("id", i);
  n++;
}

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

有什么建议吗?


<details>
<summary>英文:</summary>

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`.

I thought something like this may work but I soon came to realise that this would not work:

```js 
const getTiles = document.getElementsByClassName(tileClass);
  let n = 1;
  for (e in getTiles){
    let i = &quot;tile-&quot; + n;  
    e.setAttribute(&quot;id&quot;, i);
    n++;
}

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

尝试一下:

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

try that

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

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

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

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

&lt;div class=&quot;post&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;post&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;post&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;post&quot;&gt;
&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:

确定