Javascript jQuery 生成唯一 ID

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

jQuery generate unique IDs

javascriptphpjquery

提问by Mia

Here's what I have:

这是我所拥有的:

<a href="<?=$arItem["LINK"]?>"><?=$arItem["TEXT"]?></a>

It's a PHP array, which contains some links. I need to add an extra hash parameter #nav-linkto the end of each link.

它是一个 PHP 数组,其中包含一些链接。我需要在#nav-link每个链接的末尾添加一个额外的哈希参数。

Here's how I tried do it:

这是我尝试的方法:

<a id="likeLink" href=""><?=$arItem["TEXT"]?></a>
<script>
    $(document).ready(function () {
        $("#likeLink").attr("href", <?=$arItem["LINK"]?> + "#nav-link");
    });
</script>

But this code doesn't work because jQuery will not know which links I am linking to. So I guess that I need to generate the unique ids, but don't know how to do it.

但是这段代码不起作用,因为 jQuery 不知道我链接到哪些链接。所以我想我需要生成 unique ids,但不知道该怎么做。

回答by Scott Jungwirth

I didn't need a forever unique/random id, just something that was unique per page, and all of these solutions seemed overkill for me so I came up with this:

我不需要一个永远唯一/随机的 id,只需要每页唯一的东西,所有这些解决方案对我来说似乎太过分了,所以我想出了这个:

var uniqId = (function(){
    var i=0;
    return function() {
        return i++;
    }
})();

回答by Beri

For generating random ids you could use this one.

要生成随机 ID,您可以使用这个。

<script type="text/javascript">
function Generator() {};

Generator.prototype.rand =  Math.floor(Math.random() * 26) + Date.now();

Generator.prototype.getId = function() {
   return this.rand++;
};
var idGen =new Generator();
</script>
</html>
<body>
<!-- Place this in the body of the page content -->

   <button onclick="console.log(idGen.getId())">click</button>

</body>

回答by DAB

Since v1.9, jQueryUI has a builtin method for creating unique id's, called uniqueId().

从 v1.9 开始,jQueryUI 有一个用于创建唯一 id 的内置方法,称为 uniqueId()。

This code will set a unique id on each element belonging to myclass.

这段代码将为属于 myclass 的每个元素设置一个唯一的 id。

$(".myclass").each(function () {
    $(this).uniqueId();
});

Note that, in my testing at least, you cannot assign a new id, if the element already has one.

请注意,至少在我的测试中,如果元素已经有一个新 ID,则不能分配新 ID。

So this div would get a unique id with the above Javascript code

所以这个 div 将使用上面的 Javascript 代码获得一个唯一的 id

<div class="myclass"/>

But this wouldn't

但这不会

<div class="myclass" id="myId"/>

See https://api.jqueryui.com/uniqueId/for more information

有关更多信息,请参阅https://api.jqueryui.com/uniqueId/

回答by Jim Ma

I always use following code to generate unique ids. I've found this method several years ago on Stackoverflow:

我总是使用以下代码来生成唯一的 ID。几年前我在 Stackoverflow 上发现了这个方法:

 /**
 * Create a random Guid.
 *
 * @return {String} a random guid value.
 */
newGuid: function() {
  return '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);
    }).toUpperCase();
}

And you are able to find other useful js helpers in my library: https://github.com/mazong1123/neatjs

您可以在我的库中找到其他有用的 js 助手:https: //github.com/mazong1123/neatjs

回答by Sajjad Ali Khan

We can create a unique id for the elements using uniqueId()in Underscore:

我们可以在 Underscore 中使用uniqueId()为元素创建一个唯一的 id :

uniqueId

 _.uniqueId([prefix]) 

Generate a globally-unique id for client-side models or DOM elements that need one. If prefixis passed, the id will be appended to it.

_.uniqueId('contact_');
=> 'contact_104'

唯一身份

 _.uniqueId([prefix]) 

为需要一个的客户端模型或 DOM 元素生成一个全局唯一的 id。如果前缀被传递,id 将被附加到它。

_.uniqueId('contact_');
=> 'contact_104'

回答by Joe Johnston

I know this is a year old now, however, the OP stated he did not know 'how' to apply the IDs. This can be accomplished easily using the rand prototype by beriabove as used here.

我知道这已经一岁了,但是,OP 表示他不知道“如何”应用 ID。这可以使用上面使用的berirand原型轻松完成。

/// insure ALL myClass elements have a unique ID. 
if(!$('.myClass').attr("id")){
    $('.myClass').attr("id",idGen.getId());
    console.log($('.myClass').attr("id"));
}

or using a much broader brush:

或使用更广泛的画笔:

/// insure ALL anchor tags have a unique ID. 
if(!$('a').attr("id")){
    $('a').attr("id",idGen.getId());
}

回答by Martin

Assuming that you call the code in some kind of loop, you could just replace

假设你在某种循环中调用代码,你可以替换

<a href="<?=$arItem["LINK"]?>"><?=$arItem["TEXT"]?></a>

with

<a href="<?=$arItem["LINK"]?>#nav-link"><?=$arItem["TEXT"]?></a>

that way "#nav-link" is added at the end of each link. No javascript or jquery needed at all :D

这样在每个链接的末尾添加了“#nav-link”。根本不需要 javascript 或 jquery :D