gpt4 book ai didi

jquery - 克隆并重命名 ID 和名称

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

我正在尝试克隆输入字段并重命名单选按钮和其他控件的 ID 和名称。克隆工作正常,但名称没有被重命名。我想将单选按钮名称“radio_1”重命名为“radio_2”等。这是我的代码。

<form name="form1" id="my_form" method="post" action="">
<div><input type="text" id="text_1" name="text_1"/> </div>
<div><label><input type="radio" id=radio1_1" name="radio_1" value="1">Yes</label>
<label><input type="radio" id=radio1_1" name="radio_1" value="2">No</label>
</div>

<!-- Cloned markup-->

<div><label><input type="radio" id=radio1_2" name="radio_2" value="1">Yes</label>
<label><input type="radio" id=radio1_2" name="radio_2" value="2">No</label>
</div>
---------------
<input type="submit" value="Submit">
</form>

以下代码似乎不起作用。

var settings = {
newid_ : 0,
target_: $(this),
insert_: "before",
limit_: 0
};
var srcid = 1;
$(fieldclone).find('input, select, textarea').each(function(){
var s = $(this).attr("name");
$(this).attr("name", s.replace(eval('/_'+srcid+'/ig'),'_'+settings.newid_));
var s1 = $(this).attr("id");
$(this).attr("id", s1.replace(eval('/_'+srcid+'/ig'),'_'+settings.newid_));
});

最佳答案

这就是我用于此类事情的方法,您也许可以根据您的应用程序调整它:

(function($){
$.fn.cloneAndIncrement = function(newIndex) {
var newItem = this.clone();
newItem.find("[name]").each(function() {
$(this).attr("name", $(this).attr("name").replace( /\[\d\]/ , "[" + newIndex + "]"));
});
newItem.find("[data-valmsg-for]").each(function() {
$(this).attr("data-valmsg-for", $(this).attr("data-valmsg-for").replace( /\[\d\]/ , "[" + newIndex + "]"));
});
newItem.find("[id]").each(function() {
$(this).attr("id", $(this).attr("id").replace( /_\d_/ , "_" + newIndex + "_"));
});
newItem.attr("id", newItem.attr("id").replace( /_\d_/ , "_" + newIndex + "_"));
newItem.find("input[name$='.Index']").val(newIndex);
var entityId = newItem.find("input:hidden[name$='.Id']");
if (entityId)
entityId.val(0);
return newItem;
};
})($);

请注意,它是为 ASP.NET MVC 应用程序制作的,因此期望输入名称为 Index。它还调整一些不显眼的验证属性并将 ID 属性归零(因为在我的应用程序中,这些克隆的输入用于将其他项目插入到数据库中)。

请注意,我的惯例是使用括号来跟踪索引项。您想要将该正则表达式更改为如下所示(警告,未经测试!):

newItem.find("[name]").each(function() {
$(this).attr("name", $(this).attr("name").replace( /\_\d\/ , "_" + newIndex));

关于jquery - 克隆并重命名 ID 和名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8187282/

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