代码之家  ›  专栏  ›  技术社区  ›  Lime

Javascript将属性拆分为对象排除在字符串内部

  •  1
  • Lime  · 技术社区  · 14 年前

    var cssProperties = 'background:green;content:"Content;";color:pink;';
    

    上述情况应导致以下结果

    var theObject = {
        background:'green',
        content:'"Content;"',
        color:'pink'
    }
    

    不幸的是,由于url中有分号,我不能只使用split(“;”)和循环遍历数组。我可以创建一个巨大的循环,在跳过“;”的同时循环遍历每个字符,但这似乎有点不对。

    可选:

    3 回复  |  直到 14 年前
        1
  •  2
  •   Lime    14 年前

    下面是进一步演示该功能的小提琴: http://jsfiddle.net/ZcEUL/

    (function() {
        var div = document.createElement('div'),
            rprops =/[\w-]+(?=:)/g,
            rcamelCase = /-(\D)/g,
            fcamelCase = function(a,letter) {
                    return letter.toUpperCase();
                };
        window['styleToObject'] = function(str) {
            var props = str.match(rprops),
                prop, i = 0,
                theObject = {};
            div.style.cssText = str;
            while (prop = props[i++]) {
                var style=div.style[prop.replace(rcamelCase,fcamelCase)];
                if (style) {
                    theObject[prop] = style;
                }
            }
            return theObject;
        };
    })();
    
        2
  •  1
  •   subhaze    14 年前

    下面是我对你列出的第一个css字符串的解决方案。。。不是最好的,但也许会有助于激发一些想法。

    JSFiddle Example

        3
  •  0
  •   Slappy    14 年前

    试试这个或类似的

    var newString = cssProperties
                       .replace(":", ":'")
                       .replace(";", ", '");
    var obj = eval(newString);