[英]Create cloned numbered forms dynamically with 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/
更改表格:
<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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.