如何克隆一个 div 并更改克隆的 div 中的 HTML 数据

时间:2021-02-02 02:42:45

标签: javascript html jquery

我花了很多时间在这上面,却无法弄清楚。我有一个名为 box 的 div,我想克隆它。目前,我正在 html 页面中一次又一次地为 10 个框编写代码并将它们的数据放入其中。我现在明白这不是正确的方法,因为代码变得很长。我想要的是克隆的盒子里面有不同的数据。例如框 1 中的标题和数据应与框 2 等不同。

我的尝试:我尝试通过在 for 循环中使用 JQuery 函数来使用 .clone()。效果很好,但我无法访问克隆的元素。请提供一个例子,因为我对此很陌生,浪费了很多时间。

主要目标:消除为框重写 HTML 代码(例如,如果我有 10 个框),但在 10 个框内有不同的数据。例如标题,在类图标栏 2.. 请帮帮我。谢谢!!!!

    <div class="box" id="box">
      <div class="container">
        <div class="header">
          <h3 id="Trailer_name"></h3>
        </div>
        <div class="img-container" id="image_container">
          <iframe
            style="width: 15vw; height: 18vh"
            frameborder="0"
            src="map.php"
          ></iframe>
        </div>

        <form method="post">
          <p>
            <button type="button" class="button3">
              <ion-icon class="icon2" name="contrast-outline"></ion-icon>

              LIGHTS
            </button>

            <a href=""><button class="button">ON</button></a>
          </p>
        </form>

        <form method="post">
          <p>
            <a href=""><button type="button" class="button2">OFF</button></a>
          </p>
        </form>

        <div class="icon-bar">
          <a class="active" href="#">Solar PV</a>
          <a class="active" href="#">Battery </a>
          <a class="active" href="#">Power</a>
          <a class="active" href="#">Video</a>
        </div>
        <div class="icon-bar2">
          <a class="active" href="#"> 48 </a>
          <a class="active" href="#">250 V</a>
          <a class="active" href="#">1.5KW</a>
        </div>
      </div>
    </div>

1 个答案:

答案 0 :(得分:0)

您可以使用 jquery 循环并将数据保存在数组中。现在,当循环运行时,您的数据将填充在 div 中

0 0
0 1
0 2
1 2
2 2
2 1
2 0
1 0
var things = ["Solar PV", "Battery","Power","Video"];

for (var i = 0; i < things.length; i++) {
  $("<div>"+things[i]+"</div>").appendTo("#inserts");
}

相关问题