2012-02-24 95 views
3

是否有一个快捷方式将DOM元素及其各种属性/值对转换为相应的Javascript对象?将DOM元素的属性/值对转换成Javascript对象?

例如转换该HTML页面:

<div id="snack" type="apple" color="red" size="large" quantity=3></div> 

在JavaScript对象,就好像您已键入:

var obj = { 
     id: "snack" 
     type: "apple" 
     color: "red" 
     size: "large" 
     quantity: 3 
}; 
+0

如果有ISN”这是一个插件的好主意。 – Stephen 2012-02-24 22:00:44

回答

5

不是一个真正的捷径,但至少短期实现,它你想要什么:

var attributes = document.getElementById('someId').attributes; 
var obj = {}; 

for (var i = 0, len = attributes.length; i < len; i++) { 
    obj[attributes[i].name] = attributes[i].value; 
} 
+1

我可以建议:'(var i = 0,len = attributes.length; i 2012-02-24 22:11:59

+0

同意并更新。即使AFAIK今天的js引擎在第一次击中并获得性能之后缓存对象路径。 – 2012-02-24 22:15:31

+1

我跑了[code](http://jsfiddle.net/sMX4M/),它的工作原理。 – OnesimusUnbound 2012-02-24 22:21:29

1

为什么不使用HTML数据和JQuery?

// First, append the attributes with `data-`. 
<div id="snack" data-type="apple" data-color="red" 
    data-size="large" data-quantity="3"></div> 


// Then use jQuery to retrive the data, for this case, 
// the `snack` variable is populated 
var snack = $("#snack").data(); 

for(prop in snack) { 
    alert(prop + " => " + snack[prop]); 
} 

sample code

我不知道,如果你被允许使用jQuery

+0

这太棒了!希望我可以选择两个答案。第一个回答如我所问,这对于手头的任务以一种非常有用的方式重新阐述了这个问题。 – prototype 2012-02-24 22:45:36

1

在更实用的风格,一个声明:

[].slice.call(attributes).reduce(function(obj,attr){obj[attr.name] = attr.value;return obj;},{})