2016-03-07 47 views
1

我在克隆表單的一部分時(使用jQuery)時遇到問題。MDL動畫停止複製<fieldset>

下面的代碼複製'fieldset',應用唯一的id和for,然後在原始'fieldset'中追加副本。

雖然複製工作,'MDL'框架的所有動畫在複製'fieldset'中斷開。

我使用的代碼如下所示:

//When add section is pressed 
$('#add-section').click(function() { 
    // add 2 vars to count clicks per page 

    // get the fieldset's children that user is on, and clone it 
    var $fieldsetCopy = $('form>:nth-child(' + pageNumber + ')').clone(); 

    // add '-2' to all id's of the cloned fieldset 
    $fieldsetCopy.find("*[id]").each(function() { 
     $(this).attr("id", $(this).attr("id") + "-2"); 
    }); 

    // add '-2' to all for's of the cloned fieldset 
    $fieldsetCopy.find("*[for]").each(function() { 
     $(this).attr("for", $(this).attr("for") + "-2"); 
    }); 

    // remove the first p element of the clone 
    $fieldsetCopy.find("p").first().remove(); 

    // add the cloned fieldset within the original 
    $fieldsetCopy.appendTo('form>:nth-child(' + pageNumber + ')'); 
    $() 
}); 

我猜測的一個問題是JavaScript的加載?

回答

1

我最終自己找到了答案。問題是該框架需要重新加載。要做到這一點,您可以使用該行:

componentHandler.upgradeAllRegistered(); 

或者,如果你想針對一個特定的元素,你可以使用:

componentHandler.upgradeElement(button); 

完整的文檔在這裏https://getmdl.io/started/#dynamic

0

這裏是另一個例子(沒有jQuery)。也許它會有所幫助。只需手動重建DOM。

<script type="text/javascript"> 

document.getElementById("addText").onclick = function() { 
    var form = document.getElementById("container_layout_text"); 

    var newDiv = document.createElement("div"); 
    newDiv.className = "mdl-textfield mdl-js-textfield mdl-textfield--floating-label desc_value"; 

    var newInput = document.createElement("input"); 
    newInput.className = "mdl-textfield__input"; 
    newInput.type = "text"; 

    var newLabel = document.createElement("label"); 
    newLabel.className = "mdl-textfield__label"; 
    newLabel.textContent = "kkk?"; 

    newDiv.appendChild(newInput); 
    newDiv.appendChild(newLabel); 

    componentHandler.upgradeElement(newDiv); 
    form.appendChild(newDiv); 
}