ysf*_*qbl 5 jquery jquery-clone
我试图用类".age-sex-details"克隆html div元素,并使用jquery clone函数绑定到下面显示的".age-sex-remove"和".age-sex-add"类的事件.我能够克隆div,上面提到的事件和使用.clone(true)函数输入到输入框中的数据,但我需要克隆div元素和提到的事件,但不是克隆在"count"中输入的数据和"年龄"输入字段.这可能吗?
下面的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();
});
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
谢谢,优素福
克隆元素后,可以在不带参数的情况下调用removeData():
var cloneWithEventsOnly = $("selector").clone(true).removeData();
Run Code Online (Sandbox Code Playgroud)
编辑:它看起来像要清除表单控件的值(这不应该在根据第一个地方被复制clone()的文件,但显然是).
在这种情况下,您可以将表单控件与:input选择器匹配,并使用val()清除它们的值:
var cloneWithoutValues = $("selector").clone(true).find(":input").val("").end();
Run Code Online (Sandbox Code Playgroud)
或者,在您的特定情况下:
var source = $(".age-sex-details").eq(index - 1);
source.clone(true).find(":input").val("").end().insertAfter(source);
Run Code Online (Sandbox Code Playgroud)