2012-02-26 35 views
0

我這裏有一個字段:如何克隆fieldset而不顯示給用戶?

<fieldset class="pollQuestion" id="pq1"> 
    <legend id="legend">Q&A</legend> 
    <ul> 
     <li> 
      <input type="text" id="formheader" value="Question 1""></input> 
     </li> 
     <li> 
      <input type="button" class="addQuestion" value="Add Question" /> 
      <input type="button" class="delQuestion" value="Remove Question" /> 
     </li> 
     <label>Answers</label> 
     <li id="answerFields"> 
      <input type="text" id="formanswer1" value="" /> 
     </li> 
     <li> 
      <input type="button" class="addAnswer" value="Add Answer" /> 
      <input type="button" class="delAnswer" value="Remove Answer" /> 
     </li> 
    </ul> 
</fieldset> 

我想克隆(),因爲我可以用數組的內容填充,否則我可能只是不填出來的。我想類似的功能:

$(document).ready(function() { 
    window.clone = $('#pq1').clone(); 
}); 

,但我不能得到它由於某種原因

我有一個例子小提琴here工作。

回答

0

你有兩個錯別字:

window.clone = "$('#pq1').clone()"; //remove quotes 

$('$clone').attr('id', 'pq'+newNum);應該$clone.attr('id', 'pq'+newNum);

更新fiddle

0

,將創建只有一個嘗試追加多次克隆。

但除此之外,在你的小提琴你把一個字符串window.clone = "$('#pq1').clone()"

,然後運行$clone = window.clone後您嘗試使用在一個jQuery對象$("$clone") ...東西告訴我你不知道你是什麼'正在做...

Here是更新的小提琴。我設法挽救它,以便您可以創建新問題,但是由於您嘗試訪問不存在的#btnDel,因此無法刪除它們。祝你好運...

+0

我非常感謝你回覆了這篇文章,並盡了我們的努力來解決這個問題,但是我在類似的mannar中使用了我的實際程序。我只需要在編輯之前創建一個新副本,並且我認爲在DOM負載上覆制它是最好的解決方案。這個副本是在他們編輯了字段之後不會工作的:(謝謝你的建議tho! – user1082764 2012-02-26 23:38:35

+0

那麼,沒有理由不能克隆你試圖擁有的克隆,但是,不要訪問克隆來放置它您應該克隆克隆**,以便始終擁有存儲在'window.clone'中的原始副本。 – 2012-02-26 23:40:31

0
$(document).ready(function() { 
    $(".pollQuestion").clone().appendTo("#legend"); 
}); 

如果這是你想要做的!

0

爲了克隆的元素,你可以這樣做:

$(document).ready(function() { 
    var $clone = $('#pq1').clone(); 
} 

,然後在點擊事件,使用$克隆對象(不再次聲明)。它將不會顯示,直到您將它附加到DOM。

0

試試這個:

$(document).ready(function() { 
    //store in a local variable to document.ready so as not to pollute the global namespace 
    var myClone = $('#pq1').clone(); 
    // move into document.ready so it has access to the local variable. 
    $('.addQuestion').live('click', function() { 
     var num = $("#pollContent fieldset.pollQuestion").length; 
     var newNum = new Number(num + 1); // the numeric ID of the new input field being added 
     // return a clone of the original cloned object. 
     var $clone = myClone.clone(); 
     //remove the quotes from $clone as you want to pass the jQuery constructor a jQuery object, not a selector string. 
     $($clone).attr('id', 'pq' + newNum); 
     //update the question in the text box for visual confirmation that this is working. 
     $($clone).find('#formheader').val('Question ' + newNum); 
     // insert the new element after the last "duplicatable" input field 
     $('#pq' + num).after($clone); 
     // enable the "remove" button 
     $('#btnDel').attr('disabled', ''); 
    }); 
}); 

,當然,an updated fiddle