替换jQuery中表单元素属性的一部分
我想用新值替换name属性的一部分。此值取决于原始值。name属性的值为:时隙[timeslot_1][start]替换jQuery中表单元素属性的一部分,jquery,Jquery,我想用新值替换name属性的一部分。此值取决于原始值。name属性的值为:时隙[timeslot_1][start] 如何将“时隙_1”的值递增为“时隙_2”,并用此值替换原始值 cloneElm包含两种类型的元素(输入和选择)——我希望能够在循环中捕获这两种元素 到目前为止,我掌握的代码是: $(cloneElm).children('span').children('input').each(function(id) { var newName = $(this).attr(
$(cloneElm).children('span').children('input').each(function(id) {
var newName = $(this).attr('name').replace('timeslot_1', 'timeslot_2');
$(this).attr('name', newName);
});
谢谢事实上,我不确定我的思路是否正确,因为我对你的问题有点困惑,但这里有一个尝试
$(cloneElm).children('span').children('input').each(function(id) {
var mynumber = parseInt((($(this).attr('name')).split("_"))[1]);
var newName = $(this).attr('name').replace('timeslot_' + mynumber, 'timeslot_' + (mynumber + 1));
$(this).attr('name', newName);
});
在阅读了其他一些帖子后,这可能会像这样被清理掉
$(cloneElm).find(':input').attr('name', function(i, name) {
var mynumber = parseInt(name.split("_")[1]);
return name.replace('timeslot_' + mynumber, 'timeslot_' + (mynumber + 1));
});
我认为这种更为普遍的方法是您所追求的:
$(cloneElm).find(':input').attr('name', function(i, name) {
return name.replace('timeslot_1', 'timeslot_2');
});
- 您可以将一个函数作为第二个参数传递给attr(),从而消除了对每个()的需要李>
- 要同时选择“输入”和“选择”元素,需要相应地调整选择器李>
- 最后,还可以为replace()方法提供正则表达式和函数李>
$(cloneElm).children('span').children('input, select').attr("name", function () {
return this.name.replace(/timeslot_(\d+)/, function ($0, $1) {
return "timeslot_" + (+$1 + 1);
});
});
更一般地说,这只是增加所有选择和输入字段名称属性上的数字
$(cloneElm).children('span').children('input, select').attr('name', function(i, name) {
if ((var result = name.match(/\d+$/)) && result)
return name.replace(/\d+$/,parseInt(result)+1));
});
您可以(正如许多人所指出的)使用字符串拆分和正则表达式来实现这一点,但在我看来,这有点混乱,而且可以说是不必要的
如果您使用的是jQuery 1.4.3或更高版本,则可以使用HTML5data
属性将数据存储在HTML元素中以供以后使用[1]
我将让您决定如何最好地选择所需的元素,但类似这样的内容应提供所需的功能:
<script type="text/javascript">
function inc_timeslot(elem) {
// calculate our next timeslot however we need to
var timeslot = $(elem).data("timeslot");
timeslot += 1;
// set the attribute
$(elem).attr("name", "timeslot_" + timeslot);
// and update the data attribute for next time
$(elem).data("timeslot", timeslot);
}
</script>
<!-- ... -->
<input name="timeslot_1" data-timeslot="1">
功能有限时间段(elem){
//计算下一个时间段,但我们需要
var时隙=$(elem).data(“时隙”);
时隙+=1;
//设置属性
$(elem).attr(“名称”、“时隙”+时隙);
//并为下次更新数据属性
$(elem).数据(“时隙”,时隙);
}
script
标记