我的表单有两个字段:短描述和长描述,最初表单文件名是sectionnewdescription和sectionnewldescription
我想生成克隆表单字段,这些字段生成像sectionnewdescription和sectionnewldescription.这样的名称。每次我克隆新表单时,它都应该生成表单字段名,并在sectionnewdescription之间增加id。
如何使用regex或任何其他jquery技术来实现这一点?
下面是我用于表单克隆的代码
jQuery("button.add").on("click", clone);
function clone(){
var clone = jQuery(this).parents(".pbone_section_default").clone()
.appendTo("#section_list")
.attr("id", "pbone_section_default_" + cloneIndex)
.find("*")
.each(function() {
// here we can put any logic to achieve desire element name
this.name = logic goes here;
})
.on('click','button.delete',remove);
};发布于 2016-05-11 13:22:08
可以使用.match()和.replace()来查找字符串中的数字,这是一个增量:
.each(function() {
this.name = incrementNumberinString(this.name);
});
var incrementNumberinString = function (string){
var i = parseInt(string.match(/\d{1}/g))+1;
return string.replace(/\d{1}/g, i)
}正则表达式会找到任何存在1次的数字。
有关Regex的示例,请参见这里。
注意:这只在假设输入名称中只有一个数字的情况下才能工作。
发布于 2016-05-11 13:05:01
是的,这是可以做到的(你离得很近)。假设您使用的是基于0的索引(即从section[new][0][description]开始),请尝试以下代码:
function clone(){
var $clone = $(".pbone_section_default").last(),
index = $clone.index();
$clone.clone()
.appendTo("#section_list")
.find("[name*='["+index+"]']")
.each(function(){
$(this).attr("name", $(this).attr("name").replace("["+ index +"]", "["+ parseInt(index+1) +"]"));
});
};参见这里的一个工作示例:小提琴
无论如何,我建议你改用模板引擎,比如八字胡或下划线。但是有很多..。检查这篇文章,看看哪一个更适合您的项目
https://stackoverflow.com/questions/37162795
复制相似问题