Can you define your own HTML element attributes?

泪湿孤枕 提交于 2019-12-06 23:47:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!