简体   繁体   English

访问HTML5数据属性

[英]Accessing HTML5 data attributes

I'm trying to work with HTML5 data-* attributes. 我正在尝试使用HTML5 data- *属性。 However I'm using the EasyUI framework and it's being problematic. 但是我正在使用EasyUI框架,这是有问题的。

HTML5 defines options are set as follows: <div data-options="{region:'north', title:'North Region', border:true}"> HTML5定义的选项设置如下: <div data-options="{region:'north', title:'North Region', border:true}">

But EasyUI enforces they are set like (no curly brackets): <div data-options="region:'north', title:'North Region', border:true"> 但是EasyUI强制将其设置为(无大括号): <div data-options="region:'north', title:'North Region', border:true">

Is there a way to access the attribute object without writing my own parser function? 是否可以在不编写自己的解析器函数的情况下访问属性对象? If I have to I must but I figure there must be a better way. 如果必须,但我认为必须有更好的方法。

Thanks for any help. 谢谢你的帮助。

Looking at the source, there is a method that does this. 从源头上看,有一种方法可以做到这一点。

$.parser.parseOptions(element);

Demo with just the method extracted: http://jsfiddle.net/FnJAE/ 演示仅提取了方法: http : //jsfiddle.net/FnJAE/

Note: this method is not documented, therefore it is subject to change without notice. 注意:此方法未记录,因此如有更改,恕不另行通知。

如果您知道它将始终被格式化为对象,则可以:

jsonData = JSON.parse("{" + element + "}");

Just FYI, you really dont have to do all that parsing. 仅供参考,您真的不必进行所有解析。 Though your HTML does need some change in quotes: See Reference jQuery.Data() HTML5 尽管您的HTML确实需要对引号进行一些更改: 请参见参考jQuery.Data()HTML5

HTML 的HTML

<div id="Bob" data-options='{"region":"north", "title":"North Region", "border":"true"}'></div>

Script 脚本

console.log($("#Bob").data("options").title);
// Will return String "North Region"

console.log($("#Bob").data("options").region);
// Will return String "north"

console.log($("#Bob").data("options").border);
// Will return String "true"

console.log($("#Bob").data("options")
// will return a JSON Object but it is EASY to convert to Array
var eleData = $("#Bob").data("options"),
    eleArray = new Array();
for (x in eleData) { eleArray[x] = eleData[x]; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM