我的页面只显示一个表单。这种形式是:
<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
});
关于javascript - 使用 jQuery 动态创建克隆编号表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38216906/