2016-07-06 63 views
0

我有一個只出現一個表單的頁面。這種形式是:使用jQuery動態創建克隆的編號表單

<div style="display: none" class="article_properties"> 
    <form id="article_properties_form"> 
     <p>Page Number</p> 
     <p id="pageNumber"></p> 
     <p>Subtitle</p> 
     <input type="text"> 

     <p>Text</p> 
     <textarea></textarea> 
     <input type="submit" value="Submit/Update"> 
    </form> 
    <div id="addOne" style="width: 25px; height: 25px; background-color: orange; border-radius: 50%"> 
     <p style="text-align: center; line-height: 25px">+</p> 
    </div> 
</div> <!--End of article properties div--> 

當用戶單擊#addOne div時,會創建該表單的克隆。但是,這種形式在技術上並不是相同的形式,因爲它將具有一個小的細節,這將使其具有獨特的不同。這個細節是頁碼。每次單擊#addOne div時,頁碼都會減少一個。用戶在查看當前頁面之前選擇頁碼。例如,假設用戶選擇10頁。第一個表單的頁碼爲10,下一個表單用戶點擊#addOne div將爲9,依此類推。第一種形式將始終保持爲10,第二種形式將始終保持爲9,第三種形式將始終保持爲8,依此類推。

這裏是我當前的腳本:

<script> 
    var numPages; //Global var: number of pages user wants 

    $('#addOne').click(function() { 
     $('#pageNumber').text(numPages); 
     numPages--; 
     var articlePropsTemplate = $('#article_properties_form').clone(); 
     $('#article_properties_form').append(articlePropsTemplate); 
    }); 
</script> 

我當前的代碼是產生非常奇怪的結果。當我點擊#addOne div時,表單將被複制多次而不是一次,並且按照邏輯倒計時順序不能正確顯示頁數。 此表單不會刷新,所有信息都通過Ajax中繼。

這裏的的jsfiddle:https://jsfiddle.net/9dzgg8m6/6/

+2

可以提供的jsfiddle用最小的代碼顯示你的問題? – madalinivascu

+1

順便說一句,你還沒有初始化你的'numPages'變量(它應該是'var numPages = 0')。因此,'numPages - '將會是'undefined - 1',它會產生'NaN'。 –

+0

@madalinivascu這裏的小提琴:https://jsfiddle.net/9dzgg8m6/6/ – user2896120

回答

1

改變你的形式:

<div class="article_properties"> 
    <form id="article_properties_form"> 
     <div class="form-body">//add a class to wrap the elements for cloning 
      <p>Page Number</p><p class="pageNumber"></p>//change the id to class 
      <p>Subtitle</p> 
      <input type="text"> 

      <p>Text</p> 
      <textarea></textarea> 
      <input type="submit" value="Submit/Update"> 
     </div> 
    </form> 

    <div id="addOne" style="width: 25px; height: 25px; background-color: orange; border-radius: 50%"><p style="text-align: center; line-height: 25px">+</p></div> 

</div> <!--End of article properties div--> 

和你的JS

var numPages = 10; 
$('.pageNumber').text(numPages);//add then number for the first element 

$('#addOne').click(function() 
{ 

    numPages--; 
    var articlePropsTemplate = $('.form-body:last').clone();//clone the last wrapped elements 
    $('#article_properties_form').append(articlePropsTemplate); 
    $('.pageNumber:last').text(numPages);//append the number after it was placed on the page 
}); 

https://jsfiddle.net/0738u576/

+1

很好的答案!謝謝你解釋每一步:) – user2896120

+0

請把你的解釋放在代碼之外。它會提高你的答案的質量。 –