1

我在使用 jQuery 验证插件时遇到了很多麻烦,我可以解决它的唯一方法是使用该.submitHandler属性并在其中做一些技巧。

其中检查触发器的父级是否是一个字段集,如果它有一个data-submit-handler属性,它将执行我发送到那里的任何内容。

它看起来像这样:

<fieldset data-submit-handler="SITE.Products.QA.Bindings.post">

在这种情况下,这SITE.Products.QA.Bindings.post将是一个函数。问题是我不知道如何将数据属性中的字符串解析为对象而不是字符串,因此我可以执行我引用的函数。有没有办法做到这一点?

4

1 回答 1

1

您可以使用可以解决它的助手:

// convert string representation of object in to object reference:
// @p: object path
// @r: root to begin with (default is window)
// if the object doesn't exist (e.g. a property isn't found along the way)
// the constant `undefined` is returned.
function getObj(p, r){
    var o = r || window;
    if (!p) return o;                      // short-circuit for empty parameter
    if(typeof p!=='string') p=p.toString();// must be string
    if(p.length==0) return o;              // must have something to parse
    var ps = p.replace(/\[(\w+)\]/g,'.$1') // handle arrays
              .replace(/^\./,'')           // remove empty elements
              .split('.');                 // get traverse list
    for (var i = 0; i < ps.length; i++){
        if (!(ps[i] in o)) return undefined; // short-circuit for bad key
        o = o[ps[i]];
    }
    return o;
}

// couple extensions to strings/objects

// Turns the string in to an object based on the path
// @this: the string you're calling the method from
// @r: (optional) root object to start traversing from
String.prototype.toObject = function(r){
    return getObj(this,r);
};

// Retrieves the supplied path base starting at the current object
// @this: the root object to start traversing from
// @s: the path to retrieve
Object.prototype.fromString = function(p){
    return getObj(p,this);
};

因此,示例用法:

window.foo = {
    bar: {
        baz: {
            hello: 'hello',
            world: function(){
                alert('world!');
            }
        }
    },
    list: [
        {item: 'a'},
        {item: 'b'},
        {item: 'c'}
    ]
};

var a = 'foo.bar.baz.hello';
console.log(getObj(a));    // hello
console.log(a.toObject()); // hello

var b = 'foo.bar.baz.world';
console.log(getObj(b)());  // world

var c = 'baz.hello';
console.log(getObj(c, foo.bar)); // hello
console.log(foo.bar.fromString(c)); // hello
console.log(c.toObject(foo.bar)); // hello

var d = 'foo.list[1].item';
console.log(getObj(d)); // b
于 2013-06-07T13:24:17.810 回答