我有以下 div。每当我点击按钮/链接时都需要添加
<div class="add_dependent" style="display: none;">
<div class="dependent_content">
<span>
<strong>Dependent<span class="divcount"></span></strong>
</span><span class="delete">Delete</span>
<div><strong>Relationship to you</strong></div>
<div>
<input type="radio" value="0" name="relationship" class="dependent-relation" />
<label>Partner</label>
<input type="radio" value="1" name="relationship" class="dependent-relation"/>
<label>Child under21</label>
<input type="radio" value="2" name="relationship" class="dependent-relation"/>
<label>dependent over21</label>
</div>
<div><strong>Date of birth</strong></div>
<div>
<input type="text" id="dependent-dob" name="dependent-dob" datepicker/>
<input type="hidden" id="dependent-id" name="dependent-id" />
</div>
</div>
</div>
<a href="" id="add" ><img src="../../Content/themes/base/images/addnew_depnt.png" style="border: 0px;" alt="add dependent"></a>
最初这个 div 将被隐藏。每次我点击链接(添加依赖)时都必须动态添加此 div,并且父 div 的 div id 应指定为 dependent+id(1,2,3...)。
我使用了以下脚本来完成此操作,但在 dependent1 中输入的数据会克隆到后续的 div 中。
$("body").delegate("#add", "click", function () {
var total_length = $(".add_dependent").length
$(".add_dependent:eq(0)").clone().prependTo("#dependent-details").css("display", "inline");
$(".add_dependent:last-child .divcount").append(total_length)
$(".divcount").each(function (index) {
var increment = index + 1
$(this).parents(".add_dependent").attr("id", "depend" + increment)
$(this).text(increment)
});
})
每当我点击添加依赖链接时,如何将上述 html 元素添加到现有页面?
有人可以帮我解决这个问题吗???
最佳答案
您可以使用append函数从模板div中获取html并将其注入(inject)到另一个div中进行渲染
$("#renderDiv").append($("#templateDiv").html());
fiddle :http://jsfiddle.net/Zz6wU/2/
关于javascript - 动态添加html内容到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17788783/