gpt4 book ai didi

jquery - 如何克隆 jQuery 中不包括数据的元素事件?

转载 作者:行者123 更新时间:2023-12-03 23:01:25 24 4
gpt4 key购买 nike

我正在尝试使用“.age-sex-details”类克隆 html div 元素,并使用下面所示的绑定(bind)到“.age-sex-remove”和“.age-sex-add”类的事件jquery clone功能。我可以使用 .clone(true) 函数克隆 div、上面提到的事件以及输入到输入框中的数据,但我需要克隆 div 元素和提到的事件,而不是“count”中输入的数据和“年龄”输入字段。这可能吗?

代码简要说明

下面的 jQuery 代码由文档就绪函数中的两个函数组成。你可以忽略第一个。第二个函数是我进行克隆的地方。我克隆下面 HTML 中显示的 div 元素并将其插入到其自身之后。

iQuery 代码

$(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">&nbsp;</a>
<a href="#" class="glyphicon glyphicon-plus age-sex-add">&nbsp;</a>
</div>

这是一个JSFiddle for the code

谢谢,优素福

最佳答案

您可以调用removeData()克隆元素后不带参数:

var cloneWithEventsOnly = $("selector").clone(true).removeData();

编辑:看起来您想清除表单控件值(根据clone()'s documentation,首先不应复制表单控件值) ,但显然是)。

在这种情况下,您可以将表单控件与 :input 相匹配。选择器并使用 val() 清除它们的值:

var cloneWithoutValues = $("selector").clone(true).find(":input").val("").end();

或者,在您的特定情况下:

var source = $(".age-sex-details").eq(index - 1);
source.clone(true).find(":input").val("").end().insertAfter(source);

关于jquery - 如何克隆 jQuery 中不包括数据的元素事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21054548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com