简体   繁体   中英

Accessing HTML5 data attributes

I'm trying to work with HTML5 data-* attributes. However I'm using the EasyUI framework and it's being problematic.

HTML5 defines options are set as follows: <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">

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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