Best way to add metadata to HTML elements

2019-03-17 23:34发布

I'm trying to put together a way of marking up various components in HTML that get parsed by a jQuery script and created when the page loads.

For example, at the moment I can put the following in to my page..

<a href="link.html" class="Theme-Button Theme-Button-Style-win2007 Theme-Button-iconLeft Theme-Button-AlignmentCenter Theme-Button-fullWidth">This is a button</a>

When the jQuery script finds it it'll inject the html necessary to create a button with an icon on it and all the necessary events etc.

However, this is messy and requires a lot of long class names. I'd much rather do something like this...

<a href="#" class="Theme-Button" data="{style: 'win2007', icon: 'left', align:'center', fullWidth: true}"></a>

It's not that much shorter but neater in my opinion and requires less parsing. Trouble is, I've done a little bit of research into "expandos" and I'm fairly sure some browsers won't like it and it won't validate.

Anybody got any better suggestions?

6条回答
萌系小妹纸
2楼-- · 2019-03-18 00:09

Go ahead and use an attribute for this, but use a data- prefix on it. Attributes with the prefix data- are explicitly allowed on all elements as of HTML5. Example:

<a href="#" class="Theme-Button" data-theme="{style: 'win2007', icon: 'left', align:'center', fullWidth: true}"></a>

It works today in all browsers (although the W3 validator may complain as its HTML5 support isn't quite ready for prime-time), and because it's now specified behavior, it's future-proofed.

查看更多
何必那么认真
3楼-- · 2019-03-18 00:10

Use jquery's ".data" property. This is very handy and many people don't know about it.

See this link for more information.

查看更多
狗以群分
4楼-- · 2019-03-18 00:14

Look at the jQuery .data() function.

查看更多
地球回转人心会变
5楼-- · 2019-03-18 00:18

Use xhtml with custom elements mixed in from another DTD. or use html5 with custom data- attributes

查看更多
一夜七次
6楼-- · 2019-03-18 00:20

One could also use classes for this sort of thing.

<a href="#" class="Theme-Button Style-win2007 Icon-left Align-Center FullWidth"></a>

You will have to pre define a lot of classes, but it doesn't feel too much different than handling each key value pair that you have to create.

查看更多
beautiful°
7楼-- · 2019-03-18 00:21

The Prototype library supports:

element.store("key","value")

and

element.retrieve("key","value").

Simple. Nice. Effective.

查看更多
登录 后发表回答