I can't seem to understand why I should be happy with HTML5 allowing custom attributes? Why would I use them?
I assume you're referencing the HTML5 [data-*]
attributes.
The advantage is that you can easily associate some scripting data (still semantic, but not for display) with your elements without having to insert inline javascript all over the place, and it will be valid HTML5. To do the same thing in HTML4 would require specifying a custom namespace, and add some namespaced attributes.
Say you've got a list of items for sale, you may want to store the numeric price without trying to parse a string:
<ul>
<li data-price="5">Item 1 is only $5 this week!</li>
<li data-price="1">Sale on Item 2, only $1</li>
...
</ul>
If you allow your user to mark a number of different items to buy, you can easily pull out the numeric value to display a running total.
Alternatively, you could have put the numbers in a span with a specific class, find the right span on the right item, and pull out the value that way, but [data-*]
attributes reduce the amount of markup/script necessary to do the same thing.
If you don't want to use it, you don't need to. There are many ways of associating data with elements, this is just a new one.
Additionally, the new dataset
JavaScript API provides a consistent means of declaratively accessing the values stored in [data-*]
attributes.
For jQuery users, .data()
and .attr()
can be used to access [data-*]
attributes, and I have written up a detailed answer on when you would want to use one over the other.
Custom attributes are already widely used, for example here's an example from dojoToolkit():
<div style="width: 350px; height: 300px">
<div dojoType="dijit.layout.TabContainer" style="width: 100%; height: 100%;">
<div dojoType="dijit.layout.ContentPane" title="My first tab" selected="true">
Lorem ipsum and all around...
</div>
<div dojoType="dijit.layout.ContentPane" title="My second tab">
Lorem ipsum and all around - second...
</div>
<div dojoType="dijit.layout.ContentPane" title="My last tab" closable="true">
Lorem ipsum and all around - last...
</div>
</div>
</div>
This could now be re-written so that the markup validates using attributes like data-dojoType
. They also allow you to store application specific data in your tags rather than hacking around in the class attribute.
There's a good introduction to data-* attributes on HTML5 Doctor.
Using the data-
custom attribute is future proofing your html5 page, no future browsers adhering to the spec will use data-[attribute]
therefore will not clash with your custom attribute.
I found another use for the data- attribute:
You could use the new HTML5 custom data-
attribute for tooltips: Semantic Tooltips With Pure CSS3 and HTML5.
来源:https://stackoverflow.com/questions/5032841/html5-custom-attributes-why-would-i-use-them