简体   繁体   English

在javascript中获取DOM元素哈希?

[英]Get DOM element hash in javascript?

In case the element doesn't have an ID attribute, I want to generate some kind of unique identifier that identifies the element. 如果元素没有ID属性,我想生成某种标识元素的唯一标识符。

Is there some function that can get me the object hash of the DOM element object, similar to spl_object_hash in PHP ? 是否有一些函数可以获取DOM元素对象的对象哈希,类似于PHP中的spl_object_hash? That would be unique enough. 这将是足够独特的。

Try this : 试试这个 :

var uid = function (i) {
    return function () { 
        return 'prefix-' + (++i); 
    };
}(0);

Usage : 用法:

uid(); // "prefix-1"
uid(); // "prefix-2"
if (!el.id) el.id = uid(); // "prefix-3"

There's no "object hash" in JavaScript. JavaScript中没有“对象哈希”。 You can set up your own counter to create unused "id" values. 您可以设置自己的计数器来创建未使用的“id”值。

var getUnusedId = function() {
   var counter = 0;
   return function(prefix) {
     prefix = prefix || "thelolcat";
     var theId;
     while (document.getElementById(theId = prefix + counter++));
     return theId;
   };
}();

That gives you a function you can call to get an id like "thelolcat203". 这为您提供了一个函数,您可以调用它来获取像“thelolcat203”这样的id。 Each time you call it the counter is incremented, and it checks the new value to make sure there's no such element in the document. 每次调用它时,计数器都会递增,并检查新值以确保文档中没有这样的元素。

It's not entirely safe to do that, because you don't know for sure that some content to be added dynamically won't have the same id, but it's not too hard to work with some convention that makes it pretty unlikely to have collisions. 这样做并不完全安全,因为您不确定某些动态添加的内容将不具有相同的ID,但是使用某些使其不太可能发生冲突的约定并不难。 (The jQuery library does this internally anyway.) (无论如何,jQuery库在内部执行此操作。)

That would be ridiculously taxing on the browser. 这会对浏览器造成可笑的负担。 What you're describing can be done using things built into JS already. 你所描述的内容可以使用JS中内置的东西来完成。 Either give them ID's through JS automatically or you can select them through classes, children, parents, tag names, etc. 要么通过JS自动提供ID,要么可以通过类,子项,父项,标记名等来选择它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM