每次调用函数时如何在javascript中创建唯一ID?

时间:2017-02-24 20:21:11

标签: javascript

这是功能:

function addAttachment() {
    if (allowed_attachments <= 0)
         return alert("', $txt['more_attachments_error'], '");

    document.getElementById("uploadBtn").onchange = function () {                                                
         document.getElementById("uploadFile").value = this.value;
    };


    setOuterHTML(document.getElementById("moreAttachments"), 
        \'<div class="upload_attachment">\
            <input id="uploadFile" placeholder="File">\
            <label class="custom-file-input">\
                <input type="file" id="uploadBtn" name="attachment[]">\
            </label></div><span id="moreAttachments">\
        </span>\');
    allowed_attachments = allowed_attachments - 1;
    return true;
}

UploadBtn和UploadFile每次都需要是唯一的,我该怎么做?我真的被困了

2 个答案:

答案 0 :(得分:2)

使用全局对象(超出addAttachement的范围),如下所示:

var UNIQUE_ID = 0; // the ID counter (will be incremented each time a new item is created so it'll be unique)

function addAttachment() {
    if (allowed_attachments <= 0)
         return alert("', $txt['more_attachments_error'], '");

    document.getElementById("uploadBtn").onchange = function () {                                                
         document.getElementById("uploadFile").value = this.value;
    };

    UNIQUE_ID++; // increment the ID counter

    setOuterHTML(document.getElementById("moreAttachments"), 
        '<div class="upload_attachment">\
            <input id="uploadFile' + UNIQUE_ID + '" placeholder="File">\
            <label class="custom-file-input">\
                <input type="file" id="uploadBtn' + UNIQUE_ID + '" name="attachment[]">\
            </label></div><span id="moreAttachments' + UNIQUE_ID + '">\
        </span>');
    allowed_attachments = allowed_attachments - 1;
    return true;
}

答案 1 :(得分:1)

立即使用日期对象方法Date.now()