将字符串解析为来自data属性的对象
parse a string as an object from data attribute
我有很多麻烦与jQuery验证插件和唯一的方法,我可以工作围绕它是通过使用.submitHandler
属性和做一些技巧里面。
其中一个是检查触发器的父是否是一个字段集,如果它有一个data-submit-handler
属性,它将执行我发送的任何东西。
它看起来像这样:
<fieldset data-submit-handler="SITE.Products.QA.Bindings.post">
在这种情况下SITE.Products.QA.Bindings.post
将是一个函数。问题是,我不知道如何将数据属性中的字符串解析为对象而不是字符串,以便执行我引用的函数。有办法吗?
您可以使用帮助器来解析它:
// 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
相关文章:
- jQuery可以't获取data-*属性值,返回undefined
- 为什么toStaticHTML删除data-*属性
- 访问HTML中的data-*属性并将其作为道具传递
- 如何使用jQuery选择具有特定data-属性的元素?价值无关紧要
- Javascript个性测试使用'这'和data-*属性
- 使用script元素上的html data-*属性来配置引用的脚本文件
- 将Data属性添加到元素,并从字符串中动态添加值
- 追加并替换data-*属性URL的查询字符串值
- 将变量从data属性传递给onclick函数
- “data-”属性作为超链接的一部分.HTML 到 JavaScript
- 在 React 组件中检索自定义 data-* 属性值(无事件)
- Javascript data-* 属性计算器
- Javascript 获取动态设置 data-* 属性
- 我想使用 jQuery 在 html 中使用 data-* 属性将占位符设置为文本框
- 如何监视 jQuery 中主体“data”属性何时更改
- jQuery - aria-controls vs data 属性来识别/选择 DOM 元素 - 这是首选方法
- 如何查找具有相同 data-* 属性的元素并删除重复项
- 有没有一种简单/快速的方法将“data-”属性映射到大小写混合的属性名称
- 多个 html data-* 属性和 js 函数不起作用
- 如何在 switch 语句中捆绑“data-”属性的大小写