如何制作 JavaScript 中列的克隆?

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

how to make a clone of a column js?

问题

HTML

```html
<table>
  <tr class="tab">
    <td class="one">3</td>
    <td class="one">4</td>
    <td id="shes">5</td>
    <td class="shee">6</td>
    <td class="five">7</td>
    <td class="six">8</td>
  </tr>
</table>

JS

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

HTMl

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

js

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

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,它提供了一种插入相邻元素的简单方法 -

const col2 = document.querySelectorAll("tr > td:nth-child(2)")

for (const td of col2)
  td.after(td.cloneNode(true))
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
    <td>d</td>
    <td>e</td>
    <td>f</td>
  </tr>
</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 -->

const col2 = document.querySelectorAll(&quot;tr &gt; td:nth-child(2)&quot;)

for (const td of col2)
  td.after(td.cloneNode(true))

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

&lt;table&gt;
  &lt;tr&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;2&lt;/td&gt;
    &lt;td&gt;3&lt;/td&gt;
    &lt;td&gt;4&lt;/td&gt;
    &lt;td&gt;5&lt;/td&gt;
    &lt;td&gt;6&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;a&lt;/td&gt;
    &lt;td&gt;b&lt;/td&gt;
    &lt;td&gt;c&lt;/td&gt;
    &lt;td&gt;d&lt;/td&gt;
    &lt;td&gt;e&lt;/td&gt;
    &lt;td&gt;f&lt;/td&gt;
  &lt;/tr&gt;
&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:

确定