我想使用jQuery重命名元素的id属性。我需要匹配以下内容:
第_1行
第2行
row_xx等
这是我到目前为止所拥有的:
$('.form .newsCategories .row .itemWrap .itemTop .inputBtn').each(function(index){
$(this).attr("id", $(this).attr("id").replace($(this).attr("id").match(/\[row_[0-9]+\]/), "roww_"+index));
});
但这失败了。我认为我的前任有缺陷。请帮忙
谢谢
最佳答案
如果我了解所需的结果ID,则可以执行以下操作:
this.id = "row" + index;
例如,如果要查找所有这些文件并按文档顺序对其重新编号:
$("*[id^=row]").each(function(index) {
this.id = "row" + index;
});
它使用attribute starts-with selector(
^=
)仅查找id
以“ row”开头的元素,然后按文档顺序对它们重新编号。题外话:请注意,根本没有理由使用
$(this).attr("id")
。 DOM元素本身具有id
属性,该属性直接反映id
属性。关于javascript - javascript正则表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5009766/