gpt4 book ai didi

javascript - 将元素与唯一的编号相关联

转载 作者:行者123 更新时间:2023-11-28 15:15:07 24 4
gpt4 key购买 nike

我正在寻找一种将 DOM 元素与唯一编号关联起来的方法,这样 DOM 中的其他元素就不会与该编号关联。显然,我无法使用 Id 属性,因为并非所有元素都有 Id

最明显的方法是(以某种方式)获取一个数字,该数字将给出元素在 DOM 中的位置,但我不确定这是否可行。最终,给定 DOM 中的任意元素,我希望有一种将该元素映射到数字的方法。

每个人都在问我为什么需要这样做——给定一个 DOM 元素,我需要使用该元素作为 JS 对象中的键。 JS 对象必须是字符串。因此,从技术上讲,我本身不需要唯一的数字,但我需要一个可以转换为“短字符串”并用作 JS 对象中的键的唯一值。

最佳答案

Technically, I do not need a unique number, per se, but I need a unique value that can be turned into a "short string" and used as the key in a JS object.

我看到您已标记 jQuery。这可能是解决您的问题的可能方法。 jQuery 有一种将元素与对象关联起来的方法:

var ele = /* your element */
$(ele).data({name: "Paul"});

// later you can use the element as a key
$(ele).data(); //returns {name: "Paul"}

这将避免整个“分配唯一 id”的困惑,让 jQuery 为您完成所有艰苦的工作(创建 map 数据结构)。

<小时/>

编辑Roamer-1888

Basically, I need to "tag" an element uniquely so that if I encounter the same element in the future, I will know I've seen it before. The "tag" value will be the key in my JS object. I will associate various values in the tagged element. I don't want to use Map or WeakMap because they might not be supported on all browsers.

为了满足此要求,您通常会使用 jQuery 的 .data(),如下所示:

//...
var elementData = $(ele).data('myApplication');
if(!elementData) { // this element was not previously encountered
elementData = {
prop_A: ...,
prop_B: ...,
prop_C: ...
};
$(ele).data('myApplication', elementData);
}
// Here `elementData` is guaranteed to exist and its properties can be read/written.
//...

此技术对于在 jQuery 插件中保存状态特别有用。 Here is an example

多个应用程序/模块可以在互不干扰的情况下执行此操作。

关于javascript - 将元素与唯一的编号相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34348443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com