我有一个动态复制的字段。 一切工作正常,除了我似乎无法更改输入字段和父范围的类。
标记:
<td class="small-text">
<span class="wpcf7-form-control-wrap submitted-file">
<input type="file" name="submitted-file-1" value="1" size="40" class="wpcf7-form-control wpcf7-file submitted-file" id="submitted-file-1">
</span>
</td>
(编辑一:这不是完整的标记,只是相关部分。整个重复字段是一个完整的表行<tr>
,id为#o99_the_work
,正如人们可以从脚本中理解的那样。)
JS:
jQuery("#add_row").click(function() {
var row = jQuery("#o99_the_work tbody > tr:last"),
newRow = row.clone(true);
newRow.find("input[type=text],input[type=file]").each(function() {
var me = jQuery(this).parent();
var me2 = jQuery(this);
var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
this.id = this.id.replace(/\d+$/, "") + num;
this.name = this.id;
me2.attr("class",me2.attr("class").replace(/\d+/, function(val) { return parseInt(val)+1; }));
});
newRow.insertAfter(row);
return false;
});
因此,使用此脚本, id
和name
正确递增。
那问题出在哪里呢?我还需要增加类属性 submitted-file
在输入字段和父范围上,但是这一行:
me2.attr("class",me2.attr("class").replace(/\d+/, function(val) { return parseInt(val)+1; }));
实际上捕获了第一个数字,在我的例子中是 wpcf7-form-control
,并将该值增加到 wpcf8-form-control
, wpcf9-form-control
..(这对我来说是错误的)
如何仅增加具有 submitted-file[-something]
的值?
最佳答案
问题出在 replace()
方法中的正则表达式 - 您应该搜索该数字的最后一次出现。
me2.attr("class",me2.attr("class").replace(/\d+$/, function(val) { return parseInt(val)+1; }));
关于javascript - Jquery,当类不是第一个时递增类正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18670424/