简体   繁体   English

DOM对象可以是Javascript数组中的索引/键吗?

[英]Can a DOM object be an index/key in Javascript array?

Would like to maintain a map/hash of DOM objects. 想要维护DOM对象的map / hash。 Can they serve as key objects? 他们可以作为关键对象吗? If not, what are the alternatives, please? 如果没有,请问有哪些替代方案? If there are better ways - kindly enlist them as well. 如果有更好的方法 - 也请他们加入。

You can put anything as the key, but before actual use it is always converted to string, and that string is used as a key. 您可以将任何内容作为键,但在实际使用之前,它总是转换为字符串,并且该字符串用作键。 So, if you look at what domObject.toString() produces, you see it is not a good candidate. 所以,如果你看看domObject.toString()产生了什么,你会发现它不是一个好的候选者。 If all of your dom objects have an id, you could use that id. 如果所有dom对象都有id,则可以使用该id。 If not, and you still desperately need a key based on DOM object, you probably could do with using, for example, _counter attribute with automatic counter in background putting new unique value in a DOM object if _counter is not yet present. 如果没有,并且你仍然迫切需要一个基于DOM对象的键,你可能可以使用例如_counter属性和背景中的自动计数器,如果_counter尚未存在,则将新的唯一值放入DOM对象中。

window already maintains all DOM objects as properties. window已将所有DOM对象维护为属性。 Instead of putting your own keys for each 'DOM object' try to use window or document object and methods that uses index based on the layout of DOM tree. 不是为每个'DOM对象'放置自己的密钥,而是尝试使用窗口或文档对象以及使用基于DOM树布局的索引的方法。

最简单的方法是在元素上设置数据属性。

不,但您可以在包含数字的DOM元素上设置一个属性,您可以将其作为数字索引数组中的索引。

No, because object keys are strings. 不,因为对象键是字符串。

You'd have to "serialise" your objects by id or something, then perform a lookup later. 您必须通过id或其他东西“序列化”对象,然后再执行查找。 Probably not worth it, depending on what your actual goal is here. 可能不值得,取决于你的实际目标是什么。

Not exact. 不确切。 But I think you want something like below. 但我想你想要下面这样的东西。 You can do with jquery , 你可以用jquery

The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. .serializeArray()方法创建一个JavaScript对象数组,可以编码为JSON字符串。 It operates on a jQuery object representing a set of form elements. 它在表示一组表单元素的jQuery对象上运行。 The form elements can be of several types 表单元素可以是几种类型

Refer below link : http://api.jquery.com/serializeArray/ 请参阅以下链接: http//api.jquery.com/serializeArray/

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

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