有没有办法将唯一 ID 分配给克隆节点创建的项目?

Is there way to target assign unique ids to items creating by cloning node?

我正在根据浏览器的大小创建一个网格 window。 javascript 正确构建了网格,但我无法定位 individual 元素,因为 none 带有 ID class。有没有办法在 'clone'?

时分配它

正文包含以下内容,克隆目标列表 class。在每个列表 class 中有一个 div class,带有一个由 CSS 生成的圆圈。理想情况下,我可以同时定位列表 class 和其中的 div class。

<div class="gallery">
  <h1>Dot Dot Dot Test</h1>
  <ul class="gallery__list span1">
    <li class="center repeat">
    <div class="circle">
    </div>
    </li>
  </ul>
<h1>That's All Folks!</h1>

这里是 javascript,我希望它在构建网格时自动生成唯一 ID。

<script>
        var w = window.innerWidth;
        var h = window.innerHeight;
        var numberOfColumns = Math.round(w/40);
        var numberOfRows = Math.round((h-200)/40);
        var numberOfDots = numberOfColumns * numberOfRows;
    function backgroundDots(node, count, deep) {
        for (var i = 0, copy; i < count - 1; i++) {
        copy = node.cloneNode(deep);
        node.parentNode.insertBefore(copy, node);

    }
}

backgroundDots(document.querySelector('.repeat'), numberOfDots, true);


    
    </script>

非常感谢任何帮助。已经尝试和搜索了很长时间,但似乎无法找到 work/find 解决方案。

谢谢,

罗布

不确定我是否理解正确,但您可以在将其插入 DOM 之前设置一个 ID(或任何其他属性)。类似于:

  ...
  copy = node.cloneNode(deep);
  copy.id = `id-${i}`;
  node.parentNode.insertBefore(copy, node);
  ...