Jquery-clone () add

I ran into a whlie problem trying to clone a parent div and then adding it directly under myself. My function works fine while the last node is selected like this:

 <div>
 <div> A </div>
 <div> B </div>
 <div> C </div>
   </div>

will result in

<div>
 <div> A </div>
   <div> A.1 </div> 
 <div> B </div>
 <div> C </div>
   </div>

If I clone A. But if I clone A again, I will receive.

<div>
 <div> A </div>
   <div> A.1 </div>
 <div> A </div>
   <div> A.1 </div>
 <div> B </div>
 <div> C </div>
   </div>

while I would like

<div>
 <div> A </div>
   <div> A.1 </div>
   <div> A.1 </div>
 <div> B </div>
 <div> C </div>
   </div>

My markup and code is below:

<div id="maindiv">
 <div>
  <label>First</label> 
  <input type="button" class="repeat1" onclick="Repeat(this)"/>
 </div>
 <div>
  <label>Second</label> 
  <input type="button" class="repeat1" onclick="Repeat(this)"/>
 </div>
 <div>
  <label>Third</label> 
  <input type="button" class="repeat2" onclick="Repeat(this)"/>
 </div>

</div>

function Repeat(obj)
{
 var CurrentDiv = $(obj).parents("div[class^='repeat']:first");
 $(CurrentDiv).clone().appendTo(CurrentDiv).end();

}

I also have a similar delete problem, where all child nodes are deleted, and I just want to delete one div. Any help would be greatly appreciated. Delete function

function Remove(obj)
    {
     var CurrentDiv = $(obj).parents("div[class^='repeat']:first");
     CurrentDiv.remove();

    }
+3
source share
3 answers

Is this what you are trying to do?

function Repeat(obj)
{
 var currentDiv = $(obj).parent("div");
 currentDiv.clone().insertAfter(currentDiv);
}

UPDATE: If you want nesting, try the following:

<div id="maindiv">
  <ul>First
   <li>
    <label>Sub-first</label> 
    <input type="button" class="repeat1" onclick="Repeat(this)"/>
   </li>
 </ul>

 <ul>Second
  <li>
   <label>Sub-second</label> 
   <input type="button" class="repeat1" onclick="Repeat(this)"/>
  </li>
 </ul>

 <ul>Third
  <li>
   <label>Sub-third</label> 
   <input type="button" class="repeat2" onclick="Repeat(this)"/>
  </li>
 </ul>   
</div>

<script>   
function Repeat(obj)
  {
    var CurrentLi = $(obj).parent("li");
    CurrentLi.clone().insertAfter(CurrentLi);
  }
</script>
+6
source

I think your markup is confusing:

<div>
 <div> A </div>
 <div> B </div>
 <div> C </div>
</div>

using this in the body of the replay:

$(obj).clone().text('A 1').insertAfter(obj);

:

<div>
 <div> A </div>
 <div>A 1</div>
 <div> B </div>
 <div> C </div>
</div>

, : $(obj).siblings('div:first').remove();

:

<div>
 <div>A 1</div>
 <div> B </div>
 <div> C </div>
</div>

, ? , siginifigance "repeat *" , , ?

+1

:

  • (1) , $.end() ; , $.end() , .

  • (2) , CurrentDiv ( ) CurrentDiv; , , .

, , A, Repeat().

, FYI, . .

+1

Source: https://habr.com/ru/post/1731097/


All Articles