我想在我的网站上显示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>
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 133
我真的很喜欢这个功能:
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*pin 79
2018编辑:我认为这个答案有一些有趣的信息,但对于任何实际应用,你应该使用Joe的答案.
在JavaScript中创建唯一ID的一种简单方法是使用Date对象:
var uniqid = Date.now();
Run Code Online (Sandbox Code Playgroud)
这为您提供了自1970年1月1日以来经过的总毫秒数,这是每次调用时的唯一值.
现在该值的问题在于您无法将其用作元素的ID,因为在HTML中,ID需要以字母字符开头.还有一个问题是,两个用户在同一时间执行操作可能会产生相同的ID.我们可以通过在ID的数字部分之前附加一个随机字母来减少这种可能性,并修复我们的字母字符问题.
var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();
Run Code Online (Sandbox Code Playgroud)
尽管如此,这仍有机会,无论多么微小.对于唯一ID,最好的选择是保持运行计数,每次都增加它,并在一个地方(即服务器上)执行所有操作.
bvm*_*der 68
以下是生成随机ID的可重用函数:
function revisedRandId() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
Run Code Online (Sandbox Code Playgroud)
//它不会以任何数字开头,因此CSS3将支持它
jfr*_*d00 27
我想这里的一些人并没有真正专注于你的特定问题.看起来你遇到的问题是将随机数放在页面中并将播放器挂到它上面.有很多方法可以做到这一点.最简单的是对现有代码进行少量更改,将document.write()结果放入页面.我通常不推荐使用document.write(),但由于你的代码已经是内联的,而你所尝试的就是将div放入内联,这是最简单的方法.在您拥有随机数的位置,您只需使用它将div和div放入页面:
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
Run Code Online (Sandbox Code Playgroud)
然后,你在jwplayer中设置代码,如下所示:
jwplayer(randomId).setup({
Run Code Online (Sandbox Code Playgroud)
整个代码块看起来像这样:
<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>
Run Code Online (Sandbox Code Playgroud)
我可能会在最后添加,生成一个真正的随机数只是为了创建一个独特的div ID是过度的.您不需要随机数.您只需要一个在页面中不存在的ID.像YUI这样的框架具有这样的功能,他们所做的只是拥有一个全局变量,每次调用该函数时它都会递增,然后将其与唯一的基本字符串组合在一起.它看起来像这样:
var generateID = (function() {
var globalIdCounter = 0;
return function(baseStr) {
return(baseStr + globalIdCounter++);
}
})();
Run Code Online (Sandbox Code Playgroud)
然后,在实际使用中,你会做这样的事情:
var randomId = generateID("myMovieContainer"); // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
Run Code Online (Sandbox Code Playgroud)
ori*_*dam 21
我喜欢这个简单的:
function randstr(prefix)
{
return Math.random().toString(36).replace('0.',prefix || '');
}
Run Code Online (Sandbox Code Playgroud)
由于 id 应该(尽管不是必须)以字母开头,因此我会像这样使用它:
let div_id = randstr('youtube_div_');
Run Code Online (Sandbox Code Playgroud)
一些示例值:
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
Run Code Online (Sandbox Code Playgroud)
Sta*_*ale 15
我还需要一个随机ID,我使用base64编码:
btoa(Math.random()).substring(0,12)
Run Code Online (Sandbox Code Playgroud)
选择你想要的多个字符,结果通常至少为24个字符.
Iho*_*hor 11
基于HTML 4,id应该从字母开始:
ID和NAME令牌必须以字母([A-Za-z])开头,后面可以跟任意数量的字母,数字([0-9]),连字符(" - "),下划线("_") ,冒号(":")和句号(".").
因此,其中一个解决方案可能是(字母数字):
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);
Run Code Online (Sandbox Code Playgroud)
另一个解决方案 - 仅生成带字母的字符串
var length = 9;
var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);
Run Code Online (Sandbox Code Playgroud)
为了生成随机 ID,您还可以使用标准crypto
API 及其randomUUID()
函数,该函数在 Node.js (>=v16.7.0) 和所有相关浏览器中可用:
const uuid = crypto.randomUUID()
console.log(uuid)
// prints e.g. "7f3f4512-fcf9-45fe-b726-512bba403426"
Run Code Online (Sandbox Code Playgroud)
或者你可以使用 Cripto,因为它已经内置了(除了 IE11,我发誓这些家伙已经好几年没有更新了!)
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples
var id = new Uint32Array(10);
window.crypto.getRandomValues(id);
Run Code Online (Sandbox Code Playgroud)
我还发现了这个:
let length = 32;
let id = crypto.randomBytes(length).toString("base64");
Run Code Online (Sandbox Code Playgroud)
有很多方法可以做到这一点,但对于大多数人来说,没有理由重新发明轮子:)