Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

html - HTML5 custom attributes - Why would I use them?

I can't seem to understand why I should be happy with HTML5 allowing custom attributes? Why would I use them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...