uniqid() in javascript/jquery?

前端 未结 8 1890
孤城傲影
孤城傲影 2021-01-02 09:58

what\'s the equivalent of this function in javascript:

http://php.net/manual/en/function.uniqid.php

Basically I need to generate a random ID that looks like:

8条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 10:48

    All answers here (except phpjs) don't generate unique IDs because it's based on random. Random is not unique !

    a simple solution :

    window.unique_id_counter = 0 ;
    var uniqid = function(){
        var id ;
        while(true){
            window.unique_id_counter++ ;
            id = 'uids_myproject_' + window.unique_id_counter ;
            if(!document.getElementById(id)){
                /*you can remove the loop and getElementById check if you 
                  are sure that noone use your prefix and ids with this 
                  prefix are only generated with this function.*/
                return id ;
            }
        }
    }
    

    It's easy to add dynamic prefix if it's needed. Just change unique_id_counter into an array storing counters for each prefixes.

提交回复
热议问题