如何制作 JavaScript 中列的克隆?

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

how to make a clone of a column js?

问题

  1. HTML
  2. ```html
  3. <table>
  4. <tr class="tab">
  5. <td class="one">3</td>
  6. <td class="one">4</td>
  7. <td id="shes">5</td>
  8. <td class="shee">6</td>
  9. <td class="five">7</td>
  10. <td class="six">8</td>
  11. </tr>
  12. </table>

JS

  1. let elem = document.querySelectorAll('td.one');
  2. elem.forEach((el) => {
  3. el.insertAdjacentHTML('afterend', "<td>clone td.one(number)</td>");
  4. });
英文:

HTMl

  1. &lt;table&gt;
  2. &lt;tr class=&quot;tab&quot;&gt;
  3. &lt;td class=&quot;one&quot;&gt;3&lt;/td&gt;
  4. &lt;td class=&quot;one&quot;&gt;4&lt;/td&gt;
  5. &lt;td id=&quot;shes&quot;&gt;5&lt;/td&gt;
  6. &lt;td class=&quot;shee&quot;&gt;6&lt;/td&gt;
  7. &lt;td class=&quot;five&quot;&gt;7&lt;/td&gt;
  8. &lt;td class=&quot;six&quot;&gt;8&lt;/td&gt;
  9. &lt;/tr&gt;
  10. &lt;/table&gt;

js

  1. let elem = document.querySelectorAll(&#39;td.one&#39;);
  2. elem.forEach((el) =&gt; {
  3. el.insertAdjacentHTML(&#39;afterend&#39;, &quot;&lt;td&gt;clone td.one(number)&lt;/td&gt;&quot;);
  4. });

how to clone column information ".one"

I tried using cloneNode but how to do it in .forEach don't understand

答案1

得分: 1

您可以使用 tr &gt; td:nth-child(…),其中 是要复制的列的编号。然后使用 Element.after,它提供了一种插入相邻元素的简单方法 -

  1. const col2 = document.querySelectorAll("tr > td:nth-child(2)")
  2. for (const td of col2)
  3. td.after(td.cloneNode(true))
  1. <table>
  2. <tr>
  3. <td>1</td>
  4. <td>2</td>
  5. <td>3</td>
  6. <td>4</td>
  7. <td>5</td>
  8. <td>6</td>
  9. </tr>
  10. <tr>
  11. <td>a</td>
  12. <td>b</td>
  13. <td>c</td>
  14. <td>d</td>
  15. <td>e</td>
  16. <td>f</td>
  17. </tr>
  18. </table>

这段代码可以在表格中复制第二列并将其插入到相邻的位置。

英文:

You could use tr &gt; td:nth-child(…) where is the number of the column to copy. Then use Element.after which offers a straightforward way to insert adjacent elements -

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

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

  1. const col2 = document.querySelectorAll(&quot;tr &gt; td:nth-child(2)&quot;)
  2. for (const td of col2)
  3. td.after(td.cloneNode(true))

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

  1. &lt;table&gt;
  2. &lt;tr&gt;
  3. &lt;td&gt;1&lt;/td&gt;
  4. &lt;td&gt;2&lt;/td&gt;
  5. &lt;td&gt;3&lt;/td&gt;
  6. &lt;td&gt;4&lt;/td&gt;
  7. &lt;td&gt;5&lt;/td&gt;
  8. &lt;td&gt;6&lt;/td&gt;
  9. &lt;/tr&gt;
  10. &lt;tr&gt;
  11. &lt;td&gt;a&lt;/td&gt;
  12. &lt;td&gt;b&lt;/td&gt;
  13. &lt;td&gt;c&lt;/td&gt;
  14. &lt;td&gt;d&lt;/td&gt;
  15. &lt;td&gt;e&lt;/td&gt;
  16. &lt;td&gt;f&lt;/td&gt;
  17. &lt;/tr&gt;
  18. &lt;/table&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月17日 22:18:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76036151.html
匿名

发表评论

匿名网友

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

确定