2016-07-07 131 views
1

我需要重新和我的模板DIV追加到按鈕單擊父DIV,這是可以做到多次附加元素使用jQuery選擇

<div id = "parent"> 
    <div id = "child_1"> 
     <div><input type = "text"></div> 
     <div><input type = "text"></div> 
     //several inputs and divs 
    </div> 
</div> 

和我的腳本

//on button click event 
var template = $("#parent").children().last(); 
template.attr("id","child_2"); //just a sample of dynamic id 
$("#parent").append(template); 

但這不工作

回答

2

你需要clone()你追加前孩子的副本,否則你只是把當前元素放回原來的位置。

var template = $("#parent").children().last().clone(); 

Working example

+0

感謝,工作只是我希望它的方式 – natsu1627

0

試試這個:

var html = $("#parent").html(); 
 
var i = 1; 
 

 
$("button").on("click",function(){ 
 
    i++; 
 
    $("#parent").append(html.replace('id="child_1"','id="child_' + i + '"')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id = "parent"> 
 
    <div id = "child_1"> 
 
     <div><input type = "text"></div> 
 
     <div><input type = "text"></div> 
 
     //several inputs and divs 
 
    </div> 
 
</div> 
 
<button>Click</button>