2017-10-21 36 views
0

嗨,我是編程的初學者,並且陷入了一個問題。我已經克隆了一個表單,現在除了最後一個孩子(元素)之外,我想清空它。我已經嘗試了以下,但不起作用。對已經動態創建的表單執行操作

var originalform = $('form.defaultForm').last(); //this gets the form end. 

var form_template = $('form.defaultForm').first(); //this gets the form that is then cloned 

var newform = form_template.clone(); //this clones the form 

newform.insertAfter(originalform); //inserts the form after the original form 

newform.addClass("mynewform"); //add class to new form 

$('form.mynewform:not(:last)').empty(); //empty everything in the new form except the last child(element) this doesn't work 
+1

'form.mynewform:沒有(:最後一個)'選擇各種形式與類,不屬於_their_父的最後一個孩子。你希望'form.mynewform:not(:last)'選擇表單的所有_children_,而不是_its_最後一個孩子。 (嗯,那實際上需要'>'而不是空格,否則它會選擇所有_descendants_不是_their_各自父代的最後一個孩子。您需要哪一個,取決於您的表單結構。) – CBroe

+0

$('form。 。mynewform>:否(:最後)')空();你的意思是這應該工作? – Shaggy

+0

這不起作用 – Shaggy

回答

0

我不知道我是否清楚地理解你的問題,你需要什麼才達到,但在這裏是後話。

$("button").on("click", function(e){ 
 
    var $el = $('#to-clone').clone(); 
 
    $el.find("input:not(:last-child)").remove(); 
 
    $el.appendTo('#destination'); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="to-clone" style="border:1px solid;"> 
 
<input type="text" value="1"/> 
 
<input type="text" value="2"/> 
 
<input type="text" value="3"/> 
 
<input type="text" value="4"/> 
 
</form> 
 
<button>clone</button> 
 
<div id="destination" style="padding:10px;background:red;"> 
 
fff 
 
</div>

+0

這就是我想要的。但是你只指定了輸入。除了最後一個元素,我怎樣才能刪除所有內容 – Shaggy

+0

替換輸入*(星) –

+0

它的工作原理。感謝:D – Shaggy