如何使用JavaScript创建唯一标识符?

128
我有一个表单,用户可以添加多个城市的选择框。问题是每个新生成的选择框需要具有唯一的id。这可以在JavaScript中完成吗?
以下是用于选择城市的表单部分。还要注意,当选择特定州时,我使用一些PHP来填充城市。
<form id="form" name="form" method="post" action="citySelect.php">
<select id="state" name="state" onchange="getCity()">
    <option></option>
    <option value="1">cali</option>
    <option value="2">arizona</option>
    <option value="3">texas</option>
</select>
<select id="city" name="city" style="width:100px">
    
</select>

    <br/>
</form>

这是 JavaScript 代码:
$("#bt").click(function() {

$("#form").append(
       "<select id='state' name='state' onchange='getCity()'>
           <option></option>
           <option value='1'>cali</option>
           <option value='2'>arizona</option>
           <option value='3'>texas</option>
        </select>
        <select id='city' name='city' style='width:100px'></select><br/>"
     );
});

你是在使用类似于Jquery这样的框架/工具包,还是只用原生的JavaScript?另外,你能否发布一些你的代码,至少是生成的HTML输出部分? - DeaconDesperado
你最好使用单选按钮来处理这种行为。否则在Javascript中,你可以想一个名字叫做'cities',然后像'var i = 0;' 这样使用循环迭代每个选择框,执行.setAttribute('id', 'cities' + i)。getElementsByTagName('?') 在这里会有帮助。你需要提供一些HTML示例以便他人提供真正的帮助。 - Metalshark
1
你是在询问为每个新的<option id="blah">New City</option>生成唯一的id属性吗?你可以在javascript中维护对特定新DOM元素的引用,而不仅仅是它的id。因此,根据您要做什么,您不必生成唯一的ID。 - pioto
1
我相信他的意思是,他们可以列出一个或多个城市,每个城市都来自于一个选择。 - Jonathan Fingland
您可以在此处查看相同问题的答案:http://stackoverflow.com/questions/3782825/how-to-add-unique-id-to-dynamically-generated-inputs/37424649#37424649。 - Sanjay Nishad
35个回答

1
function generateId() {
       
  return Math.random().toString(36).substring(2) +
    (new Date()).getTime().toString(36);
}

console.log(generateId())

2
请发布答案和描述,而不仅仅是代码。这将有助于用户知道在哪里进行更改。 - Dilip D

1
看看这些函数,它们会帮你完成工作。
如果你想在字符串中包含大写和小写字符:

function generateId(length) {
  var id = '';
  while (id.length < length) {
    var ch = Math.random()
      .toString(36)
      .substr(2, 1);
    if (Math.random() < 0.5) {
      ch = ch.toUpperCase();
    }
    id += ch;
  }
  return id;
}

console.log(generateId(10))

只有小写字符:

function generateId(length) {
  var id = '';
  while (id.length < length) {
    id += Math.random()
      .toString(36)
      .substr(2, 1);
  }
  return id;
}

console.log(generateId(10))


1

我认为如果你真的想要一个唯一标识符,那么最好的方法是使用类库,比如:
uuiduniqueid

注意唯一标识符随机标识符不同。

仅使用日期时间毫秒值的方法是错误的。
现在的计算机足够快,能够在单个毫秒内运行多次循环迭代。

npm install uuid

导入库:

如果您正在使用ES模块

import { v4 as uuidv4 } from 'uuid';

而对于CommonJS:

const { v4: uuidv4 } = require('uuid');

用法:

uuidv4();

// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d

1
下面是一个函数(名为genID())的例子,它会递归地检查DOM的唯一性,基于你想要的id前缀/ID。
在你的情况下,你可能会这样使用它。
var seedNum = 1;
newSelectBox.setAttribute("id",genID('state-',seedNum));

function genID(myKey, seedNum) {
  var key = myKey + seedNum;
  if (document.getElementById(key) != null) {
    return genID(myKey, ++seedNum);
  } else {
    return key;
  }
}

console.log(genID('key', 1))


0

这是我基于创建元素的xpath所做出的个人看法:

/** Returns the XPATH of an element **/
var getPathTo = function(element) {
  if (element===document.body)
      return element.tagName;

  var ix= 0;
  var siblings= element.parentNode.childNodes;
  for (var i= 0; i<siblings.length; i++) {
      var sibling= siblings[i];
      if (sibling===element)
          // stripped xpath (parent xpath + tagname + index)
          return getPathTo(element.parentNode)+ element.tagName + ix+1;
      if (sibling.nodeType===1 && sibling.tagName===element.tagName)
          ix++;
   }
}

/** hashcode function (credit https://dev59.com/XWsz5IYBdhLWcg3w2Lpu **/
var hashCode = function(str) {
  var hash = 0, i, chr, len;
  if (str.length === 0) return hash;
  for (i = 0, len = str.length; i < len; i++) {
    chr   = str.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
 }
return hash;
};

/** Genaretes according to xpath + timestamp **/
var generateUID = function(ele)
{
  return hashCode(getPathTo(ele)) + new Date().getTime();
}

首先获取元素的xpath。
然后计算xpath的哈希码。因此,每个xpath都有一个唯一的ID。
问题在于,如果动态生成唯一元素,则xpath不一定是唯一的。因此我们在末尾添加时间戳。
也许我们还可以通过添加最终的Math.Random()来保证更唯一的元素。

0
这可以通过使用随机日期来实现。
const uniqueId = new Date(Math.ceil(Math.random() * 1e13)).valueOf().toString(36);

// Sample output: '1x7kf3ygb'

或者

const unique = window.btoa(new Date(Math.ceil(Math.random() * 1e13)).getTime());

// Sample output: 'MjA5MTQzOTQ4MDk2'

0

const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);

// if u want to check for collision
const arr = [];
const checkForCollision = () => {
  for (let i = 0; i < 10000; i++) {
    const el = generateUniqueId();
    if (arr.indexOf(el) > -1) {
      alert('COLLISION FOUND');
    }
    arr.push(el);
  }
};

console.log(generateUniqueId())


0
我使用了这个函数生成了一个非数字的唯一ID,所以我想分享一下 :)
const id = btoa((Math.random(0,(new Date()).getTime())).toString()).slice(0, -10);

出于数据库 varchar 限制的原因,我对其进行了切片,但您可以自由地不使用它。


0

将随机数和毫秒级日期结合起来应该可以解决碰撞几乎没有变化的问题:

function uniqid(){
  return Math.random().toString(16).slice(2)+(new Date()).getTime()+Math.random().toString(16).slice(2);
}
console.log(uniqid()+"\r"+uniqid());


0

用于生成唯一ID的方法:

const uid = () =>
  String(
    Date.now().toString(32) +
      Math.random().toString(32) +
      Math.random().toString(32)
  ).replace(/\./g, '')

为了检查它是否工作:

var size = 500000
var arr = new Array(size)
  .fill(0)
  .map(() => uid())

var b = new Set(arr)

console.log(
  size === b.size ? 'all ids are unique' : `not unique records ${size - b.size}`
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接