javascript 自动生成唯一的 DOM id?

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

Automatically generating unique DOM ids?

javascriptjquerydom

提问by kjo

When coding with JS and the DOM I find myself constantly needing to generate ids (or names) that have no purpose other than to groupDOM elements together (or relatethem to each other)1.

当JS和DOM编码我发现自己不断地需要产生不具有比其他目的ID(或名称)DOM元素结合在一起(或涉及它们彼此)1

These ids (or names) will not be mentioned explicitly anywhere else in the code, and therefore they could be any random strings, and, for the case of ids, they must be unique.

这些 id(或名称)不会在代码的其他任何地方明确提及,因此它们可以是任何随机字符串,对于 id,它们必须是唯一的。

Is there a standard way in JavaScript to automatically generate unique ids?

JavaScript 中是否有自动生成唯一 ID 的标准方法?



1A situation that illustrates such use of identifiers arises at the time of grouping (say) radio buttons and linking them to their associated labels...

1在对(比如说)单选按钮进行分组并将它们链接到其相关标签时,会出现一种说明标识符使用的情况......

My (naive noob's) alternative to the brain-numbing task of writing HTML like this

我的(天真的菜鸟)替代像这样编写 HTML 的大脑麻木任务

<input type="radio" name="sys" id="sys-0" value="lnx"> <label for="sys-0"> Linux   </label> <br>
<input type="radio" name="sys" id="sys-1" value="osx"> <label for="sys-1"> OS X    </label> <br>
<input type="radio" name="sys" id="sys-2" value="win"> <label for="sys-2"> Windows </label>

(which requires repeating each sys-based identifier three times per button-label pair) is to just write

(这需要sys为每个按钮标签对重复每个基于标识符三遍)是只写

<div class="button-group" name="sys">
  <input type="radio" value="lnx"> <label> Linux   </label> <br>
  <input type="radio" value="osx"> <label> OS X    </label> <br>
  <input type="radio" value="win"> <label> Windows </label>
</div>

and then use some JS to group the buttons under one nameattribute, and link the labels to their respective buttons:

然后使用一些 JS 将按钮分组到一个name属性下,并将标签链接到各自的按钮:

$('.button-group').each(function (i, e) {
  var name = $(e).attr('name');
  $(e).find(':radio').each(function (j, f) {
    var id = name + '-' + j;
    $(f).attr('name', name)
        .attr('id', id)
      .next()
        .attr('for', id);
  })
});

This works fine, but it still requires me to come up with names for these button groups and unique ids for the buttons, names and ids that are otherwise useless to me. I'd just as soon avoid all this gratuitous naming business with something like

这工作正常,但它仍然需要我想出这些按钮组的名称和按钮的唯一 id,否则对我无用的名称和 id。我会尽快避免所有这些无偿的命名业务,例如

<div class="button-group">
  <input type="radio" value="lnx"> <label> Linux   </label> <br>
  <input type="radio" value="osx"> <label> OS X    </label> <br>
  <input type="radio" value="win"> <label> Windows </label>
</div>

$('.button-group').each(function (i, e) {
  var name = unique_id();
  $(e).find(':radio').each(function (j, f) {
    var id = unique_id();
    $(f).attr('name', name)
        .attr('id', id)
      .next()
        .attr('for', id);
  })
});

Of course I could roll my own implementation of unique_id, but I thought I'd ask before I reinvent this very obvious-looking wheel.

当然,我可以推出自己的 实现unique_id,但我想在我重新发明这个非常明显的轮子之前我会问一下。

采纳答案by Arun P Johny

One approach which I've used is

我使用的一种方法是

(function(){
    var counter = 0;
    window.uniqueId = function(){
        return 'myid-' + counter++
    }
});

then

然后

$('.button-group').each(function (i, e) {
  var name = uniqueId();
  $(e).find(':radio').each(function (j, f) {
    var id = uniqueId();
    $(f).attr('name', name)
        .attr('id', id)
      .next()
        .attr('for', id);
  })
});

回答by Christophe

A common approach - for example in ajax calls - is to use new Date().getTime().

一种常见的方法 - 例如在 ajax 调用中 - 是使用new Date().getTime().

If you are worried that you might output the same id twice, you can always add a validation step:

如果您担心可能会输出相同的 id 两次,您可以随时添加验证步骤:

do {uniqueID=new Date().getTime();} while (document.getElementById(uniqueID));

回答by mjswensen

I agree with some of the commenters that there are probably better ways to do this, but a simple implementation of unique_id()you could use would be:

我同意一些评论者的看法,即可能有更好的方法来做到这一点,但unique_id()您可以使用的一个简单实现是:

return Math.random().toString(36);

回答by charlietfl

Example of working with radio labels without ID:

使用没有 ID 的无线电标签的示例:

<div class="button-group" name="sys">
  <input type="radio" value="lnx" name="radio1"> <label> Linux   </label> <br>
  <input type="radio" value="osx"  name="radio1"> <label> OS X    </label> <br>
  <input type="radio" value="win"  name="radio1"> <label> Windows </label>
</div>


   <div class="content">
       <div>Show me when 1st radio checked</div> 
       <div>Show me when 2nd radio checked</div> 
       <div>Show me when 3rdd radio checked</div>
   </div>

JS

JS

$('.button-group[name=sys] :radio').change(function(){
    $(this).parent().find('label').removeClass('active');
     $(this).next().addClass('active');

      /* index radios vs content*/

      var radioIndex=$('.button-group[name=sys] :radio').index(this);
       /* hide all the content div, show one that matches radio index*/
       $('.content div').hide().eq(radioIndex).show();
})