Javascript 使用 jQuery.guid

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5612582/
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 18:03:06  来源:igfitidea点击:

using jQuery.guid

javascriptjqueryguid

提问by qwertymk

Can I use the jQuery.guidfor my own use? I have elements where I need a unique id attr so I just want to set it to jQuery.guid++like so:

我可以jQuery.guid自用吗?我有一些元素需要一个唯一的 id attr 所以我只想将它设置为jQuery.guid++这样:

var guid = jQuery.guid++;

$('<a href="#" id="a' + guid + '">link</a>').appendTo('body');

Is this safe? Will it break any code or plugins?

这安全吗?它会破坏任何代码或插件吗?

采纳答案by Daniel

It shouldn't break anything, although, if you are going to use $.guidas a global variable, there is no need to create yet another variable called guid.

它不应该破坏任何东西,但是,如果您要$.guid用作全局变量,则无需创建另一个名为guid.

Just initialize the $.guidonce and then use it directly.

只需初始化$.guid一次,然后直接使用它。

// initialize once
$.guid= 0;

// use it directly when needed
$('<a href="#" id="a' + ($.guid++) + '">link</a>').appendTo('body');

UPDATE:

更新:

It seems $.guidis used internally by jQuery for live events and shouldn't be used for DOM. You should make your own global variable and increment it yourself.

它似乎$.guid在 jQuery 内部用于实时事件,不应用于 DOM。您应该创建自己的全局变量并自己增加它。

回答by CodeRush

You can use this code to generate a Guid:

您可以使用此代码生成 Guid:

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, 
function(c) 
{
    var r = Math.random() * 16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
});