如何选择具有相同完全id的all并仅替换新随机ID的id?

时间:2011-08-13 09:23:48

标签: jquery

让我说我有:

<input type="text" id="first" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first" attribute1="test" attribute2="hello" attribute3="happy">

可能是2,3或更多。

我想选择所有具有完全“首先”ID的输入,然后使用“first_3192391”“first_9592213”这样的新ID,但它必须对每一个都是唯一的,然后将这个新的替换为“first”生成。

find("#first").each() {
   new_id = time.now();
   current_id = this.id
   this.replace(current_id, new_id)
}

类似上面的算法应该返回:

<input type="text" id="first_32931" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first_24122" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first_31292" attribute1="test" attribute2="hello" attribute3="happy">

我试图使用replaceWith()方法,但没有运气。

2 个答案:

答案 0 :(得分:1)

你需要给每个html属性一个类,然后按类选择,遍历它们然后分配id

 $(".first").each(function(){
    $(this).attr("id", Math.floor(Math.random()*1000));
    });

HTML:

 <input type="text" class="first" attribute1="test" attribute2="hello" attribute3="happy">
    <input type="text" class="first" attribute1="test" attribute2="hello" attribute3="happy">
    <input type="text" class="first" attribute1="test" attribute2="hello" attribute3="happy">

答案 1 :(得分:1)

您应该设置应用程序,以便生成有效的HTML。但是,如果无法做到这一点,您可以这样做:

$('input[id="first"]').prop('id', function(i, id) {
   return  id + '_' + i;
});

这将迭代所有具有标识first的输入字段,并将它们在集合中的索引附加到id。