引用字符串作为对象

时间:2010-05-07 22:02:21

标签: javascript

我有以下函数根据发送的数据(对象)操作元素。

function manipulateElem (elem, data) {
    for (var key in data) {
        elem[key] = data[key];
    };
}
manipulateElem(document.getElementById('test'), {'href': '/home/', 'style.color': '#000000'});

你可以想象,后来(style.color)不起作用。如何以最佳方式解决这个问题?

3 个答案:

答案 0 :(得分:0)

嗯,我猜你可以检测到字符串中的.并让它访问成员对象:

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);
        }
    };
}

答案 1 :(得分:0)

以下是如何实现此类功能的快速示例。

<!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>

答案 2 :(得分:0)

这就是你要找的东西

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"}}