generate random string for div id

后端 未结 12 732
旧时难觅i
旧时难觅i 2020-12-04 17:03

I want to display YouTube videos on my website, but I need to be able to add a unique id for each video that\'s going to be shared by users. So I put this toget

12条回答
  •  鱼传尺愫
    2020-12-04 17:55

    2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.

    A simple way to create a unique ID in JavaScript is to use the Date object:

    var uniqid = Date.now();
    

    That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.

    The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.

    var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
    var uniqid = randLetter + Date.now();
    

    This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.

提交回复
热议问题