HTML 元素的唯一标识符 [英] Unique identifier for HTML elements

查看:45
本文介绍了HTML 元素的唯一标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了 ID 之外,如果你说,你想要一个 HTML 元素的唯一标识符(比如一个 div).

Besides of the ID, if you say, you want a unique identifier for an HTML element (let say a div).

我在 DOM 中浏览了每个元素唯一的东西(如数字或字符串);但是DOM很大,我在网上没找到.

I browsed the DOM for something (like a number or string) that is unique for each element; but the DOM is big and I failed to find that in the Internet.

是否有任何属性(显然在 DOM 中)是该元素独有的?(除了ID,你也没有指定它,而是在构建DOM时出现)

Is there any property (in the DOM obviously) that is unique only to that element? (Other than the ID and also you don't specify it, but comes when the DOM is constructed)

推荐答案

正如 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;
  };
}());

这篇关于HTML 元素的唯一标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆