如何为动态生成的输入添加唯一ID?

时间:2010-09-23 21:55:37

标签: jquery

基本问题;我有这段代码:

var partipiansRow = '<div class="form-row "><input type="text" id="name" class="textbox" /> <input type="text" class="textbox" id="email" /></div>'

$(".button").live("click", function(){
    $('.form-participants').after(partipiansRow);         
});

它创建了包含2个输入的无限行,如何设置它们的唯一ID?例如:

<div class="form-row "><input type="text" id="name1" class="textbox" /> <input type="text" class="textbox" id="email1" /></div>
<div class="form-row "><input type="text" id="name2" class="textbox" /> <input type="text" class="textbox" id="email2" /></div>
<div class="form-row "><input type="text" id="name3" class="textbox" /> <input type="text" class="textbox" id="email3" /></div>

感谢。

3 个答案:

答案 0 :(得分:7)

使用计数器跟踪ID:

var nextRowID = 0;

$(".button").live("click", function(){
    var id = ++nextRowID;
    var partipiansRow = '<div class="form-row "><input type="text" id="name' + id + '" class="textbox" /> <input type="text" class="textbox" id="email' + id + '" /></div>';
    $('.form-participants').after(partipiansRow);         
});

答案 1 :(得分:0)

我们可以创建动态和唯一的ID,如

function createId() {
  return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function (c) {
    var r = Math.random() * 16 | 0;
    return r.toString(16);
  });
}

请参阅此处Brendans answer

答案 2 :(得分:-1)

使用当前时间new Date().getTime()

$(".button").live("click", function(){
    var uid           = new Date().getTime(),
        partipiansRow = '<div class="form-row' + uid + '"><input type="text" id="name' + uid + '" class="textbox" /> <input type="text" class="textbox" id="email' + uid + '" /></div>';
    $('.form-participants').after(partipiansRow);         
});