简体   繁体   English

如何动态存储有关HTML元素的信息?

[英]How to dynamically store information about HTML elements?

Should I use a data structure, like a Dictionary of data objects, keyed on element ID, or simply attach 'data-' attributes with the required data to the elements? 我应该使用像数据对象的字典这样的数据结构,键入元素ID还是仅将'data-'属性与所需的数据附加到元素? The number of properties needed to be stored for each element is only one or two. 每个元素需要存储的属性数量只有一个或两个。

Is there already a Dictionary object for JavaScript somewhere (or maybe TypeScript), or even better, an in memory database type structure I can use to manage multiple data structures together? 是否已经存在某个地方的JavaScript字典对象(或者可能是TypeScript),或者甚至更好的内存中数据库类型结构,我可以使用它来一起管理多个数据结构?

If you need to store only a couple of values I would use data- attributes - or jQuery data accessors. 如果您只需要存储几个值,则可以使用data- attribute-或jQuery data访问器。

Any object in JavaScript is a dictionary, and you can 'type' them in TypeScript easily: JavaScript中的任何对象都是字典,您可以在TypeScript中轻松地“键入”它们:

interface DictionaryOfStrings {
  [key: string]: string;
}

var a: DictionaryOfStrings;

a["first"] = "first value";
a["second"] = "second value";

for (var key in a) {
  console.log("Value of '" + key + "' is '" + a[key] + "'");
}

Any reason you can't use a simple data-binding framework like Knockoutjs for this? 有什么原因不能为此使用像Knockoutjs这样的简单数据绑定框架? This is what I'd do in this case. 这是我在这种情况下要做的。

(This is my answer, not comment, even though phrased as a question, moderators) (这是我的回答,不是评论者,即使是主持人也被提成问题)

If you do need a dictionary structure in JS, Linq.js has one you may be able to use or adapt. 如果您确实需要JS中的词典结构, Linq.js可以提供您可以使用或改编的词典结构。 TS definition files are available at Definitely Typed : TS定义文件位于“ 绝对类型”中

interface Dictionary {
    Add(key, value): void;
    Get(key): any;
    Set(key, value): bool;
    Contains(key): bool;
    Clear(): void;
    Remove(key): void;
    Count(): number;
    ToEnumerable(): Enumerable;
}

Whether you need something like this, or can rely on data- parameters, is going to come down to the detailed needs of your app, and personal choice. 无论您是需要这样的东西还是可以依赖data-参数,都将取决于您的应用程序的详细需求和个人选择。

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

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