您可以定义自己的 HTML 元素属性吗?

发布于 2024-11-27 20:01:44 字数 243 浏览 6 评论 0原文

我想知道您是否可以在 HTML 中定义自己的属性。例如,在 HTML div 中,有一系列属性,例如 styletitleclass 等。您可以编写并添加自己的属性吗?同时保持语法正确?

例如:

对此的需要是关于 Javascript 和数据的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一张白纸 2024-12-04 20:01:44

但有一个例外——没有。 HTML 使用规范定义的属性和元素,并且仅使用这些属性和元素。

该例外是 名称以 data- 开头,并且仅当您遵循 HTML 5 草案时才如此。

也就是说,在 idclass 属性中对数据进行编码通常是合适的。

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.

愁以何悠 2024-12-04 20:01:44

您可以按如下方式为任何元素定义数据属性,并使用 jQuery 数据方法轻松检索这些属性。

<div class="example" data-mydata="mydata")></div>

//In jquery to retrieve mydata you have to just say
$(".example").data("mydata");

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");
鸠魁 2024-12-04 20:01:44

语法正确——否;但是,jQuery 将毫无问题地读取您添加到 HTML 标记的任何属性。

Syntactically Correct -- NO; however, jQuery will read any attribute you add to an HTML tag without any problem.

轻许诺言 2024-12-04 20:01:44

根据记录,您可以使用 setAttribute("name","value") 将任何您想要的属性添加到带有 javascript 的元素中,

document.body.setAttribute("name","value");

并且效果很好。这也主要是跨浏览器的: quirksmode

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文