简体   繁体   English

在div中触发javascript时如何将整个div复制到另一个div

[英]Howto copy a whole div to another div when javascript is triggered in the div

I have two columns. 我有两列。 People have to select elements from the first column and it will be added to the second column. 人们必须从第一列中选​​择元素,并将其添加到第二列中。

I can use innerHTML but I never know how many elements there are going to be. 我可以使用innerHTML,但我永远不知道会有多少个元素。 So when I click the link 'MOVE' I would have to know the ID of the element (in the example element1, element2 or element3). 因此,当我单击链接“ MOVE”时,我将必须知道元素的ID(在示例element1,element2或element3中)。 Does someone know how I get the parent of the parent div where the javascript triggered? 有人知道我如何获得触发JavaScript的父div的父?

Like this: 像这样:

<div id="column1">
  <div id="element1">random tekst 1
      <div id="right">
          <a href="#" onclick="copy()">MOVE</a>
      </div>
  </div>
  <div id="element2">random tekst 2
      <div id="right">
          <a href="#" onclick="copy()">MOVE</a>
      </div>
  </div>
  <div id="element3">random tekst 3
      <div id="right">
          <a href="#" onclick="copy()">MOVE</a>
      </div>
  </div>
</div>

<div id="column2">

</div>

You can pass a reference of the anchor element to the function copy and use parentNode attribute to get the immediate parent. 您可以将anchor元素的引用传递给函数副本,并使用parentNode属性获取直接父级。

<a href="#" onclick="copy(this)">MOVE</a>

function copy(elem)
{
    alert(elem.parentNode.parentNode)
}

See parentNode 参见parentNode

Your complete copy function will be 您完整的复制功能将是

    function copy(elem)
    {
        var target = document.getElementById ( "column2");
        target.appendChild ( elem.parentNode.parentNode );
    }

Working Demo 工作演示

Note 注意

Also there is a problem with your HTML. HTML也有问题。 You have multiple elements with the same id. 您有多个具有相同ID的元素。 This is not valid. 这是无效的。 You have multiple div elements with the same id "right". 您有多个具有相同ID“右”的div元素。 Change these to unique ids. 将它们更改为唯一的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM