2016-06-08 106 views
-2

我能夠克隆一個模板並將其附加到一個div,但是,我希望能夠將克隆和追加過程中的另一個克隆的模板替換爲附加模板。jquery replacewith()函數

HTML:

<div style="display:none;" id="temp1"> 
    <p>This is a template to be cloned</p> 
</div> 
<div style="display:none;" id="temp2"> 
    <p>No, this is another temp that got cloned</p> 
</div> 
<select id="cloneOptions"> 
    <option value="0">Select One</option> 
    <option value="1">Clone 1</option> 
    <option value="2">Clone 2</option> 
</select> 
<button type="button" id="cloning">Click to clone</button> 
<div id="cloned" style="padding:2%;"></div> 

的jQuery:

$(document).ready(function() { 
    $('#cloneOptions').on('change',function(){ 
    if(this.value === "1"){ 
     $('#cloning').one('click',function() { 
     var clone = $('#temp1').clone().attr('class', 'genID'); 
     alert('Hello'); 
     $(clone).show(); 
     $('#cloned').append(clone); 
     if($('#cloned div').hasclass('genID')){ 
      $('#cloned div').replacewith(clone); 
     }     
     $('#cloneOptions').val('0'); 
     }); 
    } 
    else if(this.value === "2"){ 
     $('#cloning').one('click',function() { 
     var clone = $('#temp2').clone().attr('class', 'genID'); 
     alert('Hello'); 
     if($('#cloned div').hasclass('genID')){ 
      alert('Clone'); 
      $('#cloned div').replacewith(clone); 
     } 
     $(clone).show(); 
     $('#cloneOptions').val('0'); 
     }); 
    } 
    }); 
}); 

請參考我的小提琴:

https://jsfiddle.net/sunit2016/nLstx3so/1/

任何幫助,在此,將不勝感激。

+1

在'replacewith'中大寫'w'。 [工作小提琴](https://jsfiddle.net/nLstx3so/2/)。這個問題是關於SO的話題,應該作爲一個錯字來封閉。這對其他用戶不會有幫助。 – 4castle

+0

我怎麼會錯過它......我感到自己真是太愚蠢了,無論如何,感謝您的觀察。 –

+0

你怎麼會錯過它?你顯然沒有在瀏覽器控制檯(F12)中尋找引發的錯誤 – charlietfl

回答

1

變化replacewith變爲$('#genID').replaceWith(clone); Javascript區分大小寫。