javascript / jquery中的uniqid()?

什么是javascript中这个函数的等价物:

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

基本上我需要生成一个看起来像a4245f54345的随机ID,并以字母字符开头(所以我可以将它用作CSS id)

试试这个(在php中工作)。

 $prefix = chr(rand(97,121)); $uniqid = $prefix.uniqid(); // $uniqid = uniqid($prefix); 

尝试使用JavaScript ::

 var n = Math.floor(Math.random() * 11); var k = Math.floor(Math.random() * 1000000); var m = String.fromCharCode(n) + k; 

试试PHPJS的网站,特别是uniqid的页面

真正的问题是,您是否需要UUID符合RFC 4122标准? 你的问题似乎暗示你没有,所以创建一个仅基于Math.random()来生成这样的ID的函数并不会太难。 此外,它将比phpJS实现快得多。

这里的所有答案(除了phpjs)都不会生成唯一ID,因为它基于随机。 随机并不是唯一的!

简单的解决方案:

 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 ; } } } 

如果需要,可以轻松添加动态前缀。 只需将unique_id_counter更改为存储每个前缀的计数器的数组。

我一直在用这个……

我完全按照我的方式使用它,如果它在PHP的地方。 两者都返回相同的结果。

 function uniqid(a = "",b = false){ var c = Date.now()/1000; var d = c.toString(16).split(".").join(""); while(d.length < 14){ d += "0"; } var e = ""; if(b){ e = "."; var f = Math.round(Math.random()*100000000); e += f; } return a + d + e; } 
        

这有点令人费解,但你明白了我的要点!
示例: http //jsfiddle.net/Ng4tB/