问题
I was wondering if you can define your own attributes in HTML. For example in HTML divs there's a range of attributes, such as style
, title
, class
etc. Can you make up and add your own, while remaining syntactically correct?
For example: <div class="example" test_item="20"></div>
The need for this is with regards to Javascript and data.
回答1:
With one exception — no. HTML uses the attributes and elements defined by the specification, and only those attributes and elements.
That exception is attributes with names starting data-, and then only if you are following the HTML 5 draft.
That said, it is often appropriate to encode the data in the id
or class
attribute.
回答2:
You can define the data attribute for any element as follows, and use jQuery data method to retrieve those attributes easily.
<div class="example" data-mydata="mydata")></div>
//In jquery to retrieve mydata you have to just say
$(".example").data("mydata");
回答3:
Syntactically Correct -- NO; however, jQuery will read any attribute you add to an HTML tag without any problem.
回答4:
for the record you can add any attribute you want to an element with javascript using setAttribute("name","value")
document.body.setAttribute("name","value");
and it works fine. This is also mostly cross browser: quirksmode
来源:https://stackoverflow.com/questions/6899965/can-you-define-your-own-html-element-attributes