Reference string as object
I've got the following function that manipulates an element according to the data being sent (an object).
function manipulateElem (elem, data) {
for (var key in data) {
elem[key] = data[key];
};
}
manipulateElem(document.getElementById('test'), {'href': '/ho开发者_运维技巧me/', 'style.color': '#000000'});
As you can imagine, the later (style.color) doesn't work. How would one solve this the best way?
Here's a quick example of how you might implement such a function.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" charset="utf-8">
function manipulateElement(mainElement, props)
{
var e;
for (var prop in props)
{
var value = props[prop];
// Reset the targeted object
e = mainElement;
// Get the targeted object
prop = prop.split(".");
while (prop.length > 1) e = e[prop.shift()];
prop = prop[0];
// Set the property (or properties)
if (typeof value == 'string') {
e[prop] = value;
} else {
manipulateElement(e[prop], value);
}
}
}
window.onload = function()
{
manipulateElement(
document.getElementById("test"),
{
'href' : '/home/',
'style.color' : '#F00',
'style' : {
'backgroundColor' : '#FCC',
'padding' : '5px'
}
}
);
}
</script>
</head>
<body>
<a id="test">Test Link</a>
</body>
</html>
Well I guess you could detect the .
in the string and make it access the member object:
function manipulateElem(elem, data) {
for (var key in data) {
var parts= key.split('.');
if (parts.length===1) {
elem[key] = data[key];
} else {
var subdata= {};
subdata[parts.slice(1).join('.')]= data[key];
manipulateElem(elem[key], subdata);
}
};
}
This does what you are looking for
function foo(a, b){
for (var prop in b)
if (b.hasOwnProperty(prop)) {
var member = a, arr = prop.split("."), i, len;
for (i = 0, len = arr.length - 1; i < len; i++) {
!(arr[i] in member) && (member = member[arr[i]] = {});
}
member[arr[i]] = b[prop];
}
}
var a = {};
foo(a, {
"b": "b",
"c.d": "c.d"
});
// a = {"a":"a","c":{"d":"c.d"}}
精彩评论