HTML5自定义属性 - 我为什么要使用它们? [英] HTML5 custom attributes - Why would I use them?

查看:181
本文介绍了HTML5自定义属性 - 我为什么要使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法理解为什么我应该对允许自定义属性的HTML5感到满意? 我为什么要使用它们?

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

推荐答案

我假设你引用的是HTML5 [data - *] attributes。

I assume you're referencing the HTML5 [data-*] attributes.

好处是您可以轻松地关联一些脚本数据(仍然是语义的,但不能用于显示)使用您的元素而不必在整个地方插入内联javascript,它将是有效的HTML5。要在HTML4中执行相同的操作,需要指定自定义命名空间,并添加一些命名空间属性。

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.

或者,您可以将数字放在具有特定类的跨度中,在右边的项目上找到正确的跨度,出于这种价值,但 [data - *] 属性减少了做同样事情所需的标记/脚本的数量。

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.

此外,新的 dataset JavaScript API提供了一种声明式访问值的一致方法存储在 [data - *] 属性中。

对于jQuery用户, .data() .attr() 可用于访问 [data - *] 属性和我已经写了一个关于何时想要使用另一个的详细答案

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.

这篇关于HTML5自定义属性 - 我为什么要使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆