【问题标题】:Is there way to target assign unique ids to items creating by cloning node?有没有办法为通过克隆节点创建的项目分配唯一 ID?
【发布时间】:2021-04-28 17:58:47
【问题描述】:

我正在根据浏览器窗口的大小创建一个网格。 javascript 正确构建了网格,但是我无法定位单个元素,因为没有一个带有 ID 类。有没有办法在“克隆”时分配它?

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

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

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

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

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

谢谢,

罗伯

【问题讨论】:

    标签: javascript clonenode


    【解决方案1】:

    不确定我是否正确,但您可以在将其插入 DOM 之前设置一个 id(或任何其他属性)。比如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多