Misc information HTML element attributes
I've been using r开发者_开发百科el
to store some non-html information, what other attributes are not commonly used that I can utilize to store information?
You might want to switch to HTML5 and use custom data attributes.
In HTML5 you can define your own data-
attributes to store whatever you want.
You can make up your own attributes if you wish. It is probably not a good idea to put data into an attribute if by specification it should have something meaningful in there.
In the HTML 5 spec, you can use data-*
attributes; they're guaranteed not to do anything with the browser and they'll work in older browsers, too.
In JavaScript, you can access it with the normal attribute properties:
var value = elem.getAttribute("data-foo")
elem.setAttribute("data-foo", "value")
elem.removeAttribute("data-foo")
With new browsers you can use elem.dataset
, but you probably don't want to do that as older browsers won't support it.
var value = elem.dataset.foo;
elem.dataset.foo = "value";
elem.dataset.foo = null;
This help? Scroll down to the rel section:
http://diveintohtml5.ep.io/semantics.html
HTML5 now supports storing information in data-* attributes but thats HTML5 and everyone isn't there yet. So a real world scenario...
If you don't have to worry about persisting across post backs you could map simple data objects as a JSON collection var and pull an object out of it based on a particular key. But that is a broad approach - more information on the overall goal would improve the feedback.
Depends on what kind of information you're looking to store and how are you planning on accessing it. I successfully used both the id
and the class
attributes to store and access database IDs for example, and even references for some database tables, which I then retrieved with jQuery to do some AJAX requests.
If you are NOT using HTML5, I would advise against using your own custom attributes. Otherwise, like people already suggested before me, have a look at the data-
prefixed attributes.
data-* is the way to go if you can use HTML5. You can easily access them in javascript too with elem.data.*
Otherwise, custom attributes are probably better than screwing up the semantics of the page.
精彩评论