Javascript 替换jQuery ID
我尝试将jQuery元素的id替换为下一个元素,如下所示: “foo-1”->“foo-2” 最后,我以以下内容结束:Javascript 替换jQuery ID,javascript,jquery,string,Javascript,Jquery,String,我尝试将jQuery元素的id替换为下一个元素,如下所示: “foo-1”->“foo-2” 最后,我以以下内容结束: $(this).attr('id',$(this).attr('id').replace(/-[0-9]*/,'-'+(parseInt($(this).attr('id').substring($(this).attr('id').indexOf('-')+1,$(this).attr('id').length))+1))); 丑陋,对吧? 有没有关于如何改进此功能的想法?
$(this).attr('id',$(this).attr('id').replace(/-[0-9]*/,'-'+(parseInt($(this).attr('id').substring($(this).attr('id').indexOf('-')+1,$(this).attr('id').length))+1)));
丑陋,对吧?
有没有关于如何改进此功能的想法?使用replace回调函数简化代码:
this.id = this.id.replace(/(-)(\d)*/, function ($1,$2,$3,$4) {
console.log(arguments);
var index = parseInt($3,10);
return $2 + ++index + "";
});
$2
匹配第一个括号(在您的例子中是“-”),$3
匹配数字。然后使用parseInt()
使用数字并将其递增1。最后,将替换的字符串与+
字符串运算符组合在一起。可能类似
var num = parseInt( $(this).attr("id").replace(/[^0-9]+/g, ''));
var newid = id.replace(num, '') + (num + 1);
现场演示:您可以这样做:
var el = jQuery(this);
var old_id = el.attr('id');
var id_number = parseInt(old_id.match(/\d/), 10);
el.attr('id', old_id.replace(id_number, id_number+1));
这比您的代码有多个优点:
this.id = this.id.replace(/(-)(\d)*/, function ($1,$2,$3,$4) {
console.log(arguments);
var index = parseInt($3,10);
return $2 + ++index + "";
});
- 它缓存您正在处理的元素(如
)el
- 它缓存元素的已处理ID(如
)旧ID
- 它非常干净易读
- 它甚至比你的代码使用更少的字母
有关将ID更改为整数更高的ID的证明,请参阅。我认为这不是您的实际代码;如果是,它就不应该工作:
lenght
?attrs()不是标准的jquery方法,是输入错误还是使用自定义方法?@piskv或者很抱歉,您是对的,一个输入错误:(#edited@mamoo你说得对,我是说“attr”#EditedTanks dude。编辑后包含了一个解释和一个更一般的模式替换。有人能给我指一下.attrs()
方法的文档页面吗?jQuery文档对该方法没有说明。@t为输入错误感到抱歉。请使用正确的.attr()
函数更正。简易读取器:this.id=this.id.replace(/(-)(\d)*/,函数…
(参见)
$(this).attr('id',
function() {
var me = this;
return $(me).attr('id').replace(/[0-9]/g, '') + (parseInt($(me).index() + 1));
});
// this code snippet will assign id to element if it possess any id (like: foo-1/foo-2) or not
$(this).attr('id',
function() {
var me = this;
return ($(me).attr('id') ? $(me).attr('id').replace(/[0-9]/g, '') : 'foo-') + (parseInt($(me).index() + 1));
});