且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML元素的唯一标识符

更新时间:2023-02-07 13:49:16

Pekka说如果你描述你想做什么,这将会更容易。直到那时,这里有两个建议。

As Pekka says, it would be easier if you would describe what you want to do. Until then here are two suggestions.

除非你真的需要将id表示为某种字符串,否则可以保存正常的DOM引用。

Unless you actually need to express the id as some kind of string you can save the normal DOM reference.

如果您因为某些原因需要将其表达为字符串,那么您需要自己指定一个唯一的ID。

If you do need to express it as a string for some reason, then you'll need to assign a unique id yourself.

var getId = (function () {
  var incrementingId = 0;
  return function(element) {
    if (!element.id) {
      element.id = "id_" + incrementingId++;
      // Possibly add a check if this ID really is unique
    }
    return element.id;
  };
}());