Javascript 为 div id 生成随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6860853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:30:53  来源:igfitidea点击:

generate random string for div id

javascript

提问by sarsar

I want to display YouTube videos on my website, but I need to be able to add a unique idfor each video that's going to be shared by users. So I put this together, and I have run into a little problem. I am trying to get the JavaScript to add a random string for the div id, but it's not working, showing the string:

我想在我的网站上显示 YouTube 视频,但我需要能够为将id要由用户共享的每个视频添加一个唯一的视频。所以我把它放在一起,我遇到了一个小问题。我试图让 JavaScript 为 div 添加一个随机字符串id,但它不起作用,显示字符串:

<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

var div = randomString(8);
</script>

<div id='div()'>This text will be replaced</div>

<script type='text/javascript'>
  jwplayer('div()').setup({
    'flashplayer': 'player.swf',
    'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
    'controlbar': 'bottom',
    'width': '470',
    'height': '320'
  });
</script>

回答by Joe

I really like this function:

我真的很喜欢这个功能:

function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

From Create GUID / UUID in JavaScript?

在 JavaScript 中创建 GUID/UUID?

回答by Alex Turpin

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

2018 年编辑:我认为这个答案有一些有趣的信息,但对于任何实际应用,您应该改用Joe 的答案

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

在 JavaScript 中创建唯一 ID 的一种简单方法是使用 Date 对象:

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.

这为您提供了自 1970 年 1 月 1 日以来经过的总毫秒数,这是您每次调用.

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.

现在该值的问题是您不能将其用作元素的 ID,因为在 HTML 中,ID 需要以字母字符开头。还有一个问题是,两个用户同时执行一个操作可能会导致相同的 ID。我们可以通过在 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.

这仍然有碰撞的机会,无论多么渺茫。唯一 id 的最佳选择是保持运行计数,每次增加它,并在一个地方完成所有这些,即在服务器上。

回答by bvmCoder

Here is the reusable function to generate the random IDs :

这是生成随机 ID 的可重用函数:

function revisedRandId() {
     return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}

// It will not start with the any number digit so it will be supported by CSS3

// 它不会以任意数字开头,因此 CSS3 将支持它

回答by jfriend00

I think some folks here haven't really focused on your particular question. It looks like the problem you have is in putting the random number in the page and hooking the player up to it. There are a number of ways to do that. The simplest is with a small change to your existing code like this to document.write() the result into the page. I wouldn't normally recommend document.write(), but since your code is already inline and what you were trying do already was to put the div inline, this is the simplest way to do that. At the point where you have the random number, you just use this to put it and the div into the page:

我认为这里的一些人并没有真正关注你的特定问题。看起来您遇到的问题是将随机数放入页面并将玩家连接到它。有很多方法可以做到这一点。最简单的方法是对现有代码进行小的更改,例如将 document.write() 结果写入页面。我通常不会推荐 document.write(),但由于您的代码已经内联,并且您已经尝试将 div 内联,这是最简单的方法。在您拥有随机数的地方,您只需使用它来将它和 div 放入页面:

var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');

and then, you refer to that in the jwplayer set up code like this:

然后,您在 jwplayer 设置代码中引用如下:

jwplayer(randomId).setup({

And the whole block of code would look like this:

整个代码块看起来像这样:

<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>'); 

  jwplayer(randomId).setup({
    'flashplayer': 'player.swf',
    'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
    'controlbar': 'bottom',
    'width': '470',
    'height': '320'
  });
</script>


Another way to do it

另一种方法

I might add here at the end that generating a truly random number just to create a unique div ID is way overkill. You don't need a random number. You just need an ID that won't otherwise exist in the page. Frameworks like YUI have such a function and all they do is have a global variable that gets incremented each time the function is called and then combine that with a unique base string. It can look something like this:

我可能会在最后添加一个真正的随机数来创建一个唯一的 div ID 是一种矫枉过正的方式。你不需要随机数。您只需要一个不会出现在页面中的 ID。像 YUI 这样的框架有这样一个函数,它们所做的只是有一个全局变量,每次调用该函数时都会递增,然后将其与唯一的基本字符串组合。它看起来像这样:

var generateID = (function() {
    var globalIdCounter = 0;
    return function(baseStr) {
        return(baseStr + globalIdCounter++);
    }
})();

And, then in practical use, you would do something like this:

然后在实际使用中,你会做这样的事情:

var randomId = generateID("myMovieContainer");  // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({

回答by Staale

I also needed a random id, I went with using base64 encoding:

我还需要一个随机 ID,我使用 base64 编码:

btoa(Math.random()).substring(0,12)

Pick however many characters you want, the result is usually at least 24 characters.

选择您想要的任意多个字符,结果通常至少为 24 个字符。

回答by Ihor

Based on HTML 4, the id should start from letter:

基于HTML 4,id 应该从字母开始:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") 、冒号 (":") 和句点 (".")。

So, one of the solutions could be (alphanumeric):

因此,其中一种解决方案可能是(字母数字):

  var length = 9;
  var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter

  // Convert it to base 36 (numbers + letters), and grab the first 9 characters
  // after the decimal.
  var id = prefix + Math.random().toString(36).substr(2, length);

Another solution - generate string with letters only:

另一种解决方案 - 生成仅包含字母的字符串:

  var length = 9;
  var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);

回答by dude

A edited version of @jfriend000 version:

@jfriend000 版本的编辑版本:

    /**
     * Generates a random string
     * 
     * @param int length_
     * @return string
     */
    function randomString(length_) {

        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
        if (typeof length_ !== "number") {
            length_ = Math.floor(Math.random() * chars.length_);
        }
        var str = '';
        for (var i = 0; i < length_; i++) {
            str += chars[Math.floor(Math.random() * chars.length)];
        }
        return str;
    }

回答by oriadam

i like this simple one:

我喜欢这个简单的:

function randstr(prefix)
{
    return Math.random().toString(36).replace('0.',prefix || '');
}

since id should (though not must) start with a letter, i'd use it like this:

由于 id 应该(尽管不是必须)以字母开头,因此我会像这样使用它:

let div_id = randstr('youtube_div_');

some example values:

一些示例值:

youtube_div_4vvbgs01076
youtube_div_1rofi36hslx
youtube_div_i62wtpptnpo
youtube_div_rl4fc05xahs
youtube_div_jb9bu85go7
youtube_div_etmk8u7a3r9
youtube_div_7jrzty7x4ft
youtube_div_f41t3hxrxy
youtube_div_8822fmp5sc8
youtube_div_bv3a3flv425

回答by Jamiec

I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.

我建议您从某种占位符开始,您可能已经有了它,但它可以在某个地方附加 div。

<div id="placeholder"></div>

Now, the idea is to dynamically create a new div, with your random id:

现在,我们的想法是动态创建一个新的 div,并使用您的随机 ID:

var rndId = randomString(8); 
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";

this can be apended to your placeholder as follows:

这可以附加到您的占位符,如下所示:

document.getElementById('placeholder').appendChild(div);

You can then use that in your jwplayer code:

然后你可以在你的 jwplayer 代码中使用它:

jwplayer(rndId).setup(...);

Live example: http://jsfiddle.net/pNYZp/

现场示例:http: //jsfiddle.net/pNYZp/

Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)

旁注:我很确定 id 必须以字母字符开头(即,没有数字)-您可能想要更改 randomstring 的实现以强制执行此规则。(参考

回答by vsushkov

First. Assign an id to your div. Like this:

第一的。为您的 div 分配一个 id。像这样:

<div id="uniqueid">This text will be replaced</div>

After that, add inside your <script>tag following code:

之后,在您的<script>标签中添加以下代码:

Document.getElementById("uniqueid").id = randomString(8);