【发布时间】:2015-03-18 12:18:34
【问题描述】:
我需要找到一种方法将 DOM 中出现的所有标签映射到 key:value 字典(具有 TagName:Attributes 的结构)。 我必须使用 Javascript 或 JQuery 代码来做到这一点。
有什么想法吗?
谢谢!
【问题讨论】:
-
仅供参考 JS 没有字典类型,尽管您可以使用对象模仿相同的行为。
标签: javascript jquery html web
我需要找到一种方法将 DOM 中出现的所有标签映射到 key:value 字典(具有 TagName:Attributes 的结构)。 我必须使用 Javascript 或 JQuery 代码来做到这一点。
有什么想法吗?
谢谢!
【问题讨论】:
标签: javascript jquery html web
根据Javascript: How to loop through ALL DOM elements on a page?,您可以使用 getElementsByTagName() 列出文档的所有元素:
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
// Do something with the element here
}
看看这个Creating a .net like dictionary object in Javascript,可以像这样构建字典:
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
或者更进一步,如果你想添加特定的方法:
function Dictionary(){
var dictionary = {};
this.setData = function(key, val) { dictionary[key] = val; }
this.getData = function(key) { return dictionary[key]; }
}
var dictionary = new Dictionary();
dictionary.setData("key1", "value1");
var key1 = dictionary.getData("key1");
【讨论】: