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

查看:868
本文介绍了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天全站免登陆