我正在尝试使用 jquery 克隆具有类“.age-sex-details”的 html div 元素以及绑定到下面显示的“.age-sex-remove”和“.age-sex-add”类的事件 clone函数克隆具有类“.age-sex-details”的 html div 元素以及绑定到下面显示的“.age-sex-remove”和“.age-sex-add”类的事件. 我可以使用 .clone(true) 函数克隆 div、上面提到的事件和输入到输入框中的数据,但是我需要克隆 div 元素和提到的事件,而不是在“计数”中输入的数据和“年龄”输入字段。这可能吗?
代码简要说明
下面的 jQuery 代码由文档就绪函数中的两个函数组成。你可以忽略第一个。第二个功能是我进行克隆的地方。我克隆了下面 HTML 中显示的 div 元素,并将其插入到自身之后。
查询代码
$(document).ready(function() {
$(".age-sex-remove").click(function() {
var index = $(".age-sex-details").length;
if ( index > 1) {
$(this).parent().remove();
$($(".age-sex-add")[index - 2]).show();
} else {
console.log("only one set of age sex details, therefore clear values.")
}
});
/**
* Clone age-sex-details div including events and excluding data.
* Hide the previous add new sex age details link.
*/
$(".age-sex-add").click(function() {
var index = $(".age-sex-details").length;
console.log("Index = " +index);
$($(".age-sex-details")[index - 1]).clone(true).insertAfter($(".age-sex-details")[index - 1]);
$($(".age-sex-add")[index - 1]).hide();
});
});
HTML
<div class="form-inline age-sex-details">
<div class="form-group">
<label for="Count">Count</label>
<input type="text" name="count" class="form-control" id="Count" />
</div>
<div class="form-group">
<label for="Age">Age</label>
<input type="text" name="age" class="form-control" id="Age" />
</div>
<div class="form-group">
<label for="Sex">Sex</label>
<select name="sex" class="form-control" id="Sex">
<option value="0">Female</option>
<option value="1">Male</option>
</select>
</div>
<a href="#" class="glyphicon glyphicon-remove age-sex-remove"> </a>
<a href="#" class="glyphicon glyphicon-plus age-sex-add"> </a>
</div>
谢谢,优素福