如何使用HTML5自定义数据属性以及原因

HTML5 Custom Data Attributes

In this article, I am going to show you how you can use HTML5 custom data attributes. I’m also going to present you with some use cases that you can find helpful in your work as a developer.

在本文中,我将向您展示如何使用HTML5自定义数据属性。 我还将向您介绍一些用例,这些用例会对您作为开发人员的工作有所帮助。

为什么要使用自定义数据属性? (Why Custom Data Attributes?)

Very often we need to store information associated with different DOM elements. This information might not be essential for readers, but having easy access to it would make life a lot easier for us developers.

很多时候,我们需要存储与不同DOM元素关联的信息。 这些信息对于读者来说可能不是必不可少的,但是对它的轻松访问将使我们的开发人员的生活更加轻松。

For instance, let’s say you have a list of different restaurants on a webpage. Before HTML5, if you wanted to store information about the type of food offered by restaurants or their distance from the visitor, you would have used the HTML class attribute. What if you also needed to store the restaurant id to see which particular restaurant the user would want to visit?

举例来说,假设您在网页上列出了不同的餐馆。 在HTML5之前,如果您想存储有关餐厅提供的食物类型或其与访客的距离的信息,则应使用HTML class属性。 如果您还需要存储餐厅id以查看用户想要访问哪个餐厅,该怎么办?

Here are a few problems with the approach based on the HTML class attribute.

这是基于HTML类属性的方法的一些问题。

  • The HTML class attribute is not meant to store data like this. Its main purpose is to allow the developer to assign style information to a set of elements.

    HTML类属性并不意味着要存储这样的数据。 其主要目的是允许开发人员将样式信息分配给一组元素。
  • Each additional piece of information requires us to add a new class to our element. This makes it harder to parse the data in JavaScript to actually get what we need.

    每增加一条信息,就需要我们向元素添加一个新类。 这使得解析JavaScript中的数据以实际获得我们所需的内容变得更加困难。
  • Let’s say a given class name begins with numbers. If you decide to later style the elements based on that data in the class name, you will have to either escape the number or use attribute selectors in your stylesheet.

    假设给定的类名称以数字开头。 如果您决定以后根据类名称中的数据对元素进行样式设置,则必须转义数字或使用样式表中的属性选择器。

To get rid of these issues, HTML5 has introduced custom data attributes. All attributes on an element whose name starts with data- are data attributes. You can also use these data attributes to style your elements.

为了摆脱这些问题,HTML5引入了自定义数据属性 。 名称以data-开头的元素上的所有属性都是数据属性。 您还可以使用这些数据属性来设置元素的样式。

Next, let’s dive into the basics of data attributes and learn how to access their values in CSS and JavaScript.

接下来,让我们深入研究数据属性的基础知识,并学习如何在CSS和JavaScript中访问它们的值。

HTML语法 (The HTML Syntax)

As I mentioned earlier, the name of a data attribute will always start with data-. Here is an example:

如前所述,数据属性的名称始终以data-开头。 这是一个例子:

<li data-type="veg" data-distance="2miles" data-identifier="10318">
  Salad King
</li>

You can now use these data attributes to search and sort restaurants for your visitors. For example, you can now show them all the vegetarian restaurants within a certain distance.

现在,您可以使用这些数据属性来为访客搜索餐厅并对其进行排序。 例如,您现在可以向他们显示特定距离内的所有素食餐厅。

Besides the data- prefix, the name of a valid custom data attribute must contain only letters, numbers, hyphen (-), dot (.), colon (:) or underscore (_). It cannot contain capital letters.

data-前缀外,有效的自定义数据属性的名称必须仅包含字母,数字,连字符(-),点(。),冒号(:)或下划线(_)。 它不能包含大写字母。

There are two things that you should keep in mind when using data attributes.

使用数据属性时,应牢记两件事。

First, data stored in these attributes should be of type string. Anything that can be string-encoded can be stored in data attributes as well. All the type conversions will need to be done in JavaScript.

首先, 存储在这些属性中的数据应为string类型 。 可以进行字符串编码的任何内容也可以存储在数据属性中。 所有类型转换都需要使用JavaScript进行。

Second, data attributes should only be used when there are no other appropriate HTML elements or attributes. For example, it is not appropriate to store an element’s class in data-class attribute.

其次, 仅当没有其他适当HTML元素或attribute时才应使用 data 属性 。 例如,将元素的class存储在data-class属性中是不合适的。

An element can have any number of data attributes with any value you want.

元素可以具有任意数量的数据属性以及所需的任何值。

数据属性和CSS (Data Attributes and CSS)

You can use data attributes in CSS to style elements using attribute selectors. You can also show the information stored in the data attribute to users (in a tooltip or some other way) with the help of the attr() function.

您可以在CSS中使用数据属性来使用属性选择器来设置元素的样式。 您还可以在attr()函数的帮助下(以工具提示或其他方式)向用户显示data属性中存储的信息。

样式元素 (Styling Elements)

Getting back to our restaurant example, you can give users a cue about the type of restaurant or its distance from them using attribute selectors to style the background of the restaurants differently. Here is an example:

回到我们的餐厅示例,您可以使用属性选择器为餐厅的背景提供不同的提示,以提示用户餐厅的类型或其与餐厅的距离。 这是一个例子:

li[data-type='veg'] {
  background: #8BC34A;
}

li[data-type='french'] {
  background: #3F51B5;
}

See the Pen Styling elements with data attributes by SitePoint (@SitePoint) on CodePen.

请参阅CodePen具有 SitePoint( @SitePoint )的数据属性的笔样式元素

创建工具提示 (Creating Tooltips)

You can use tooltips to show users some additional information related to an element.

您可以使用工具提示向用户显示与元素相关的一些其他信息。

I recommend you use this method for quick prototypes rather than a production website, not least because CSS-only tooltips are not fully accessible.

我建议您将这种方法用于快速原型,而不是用于生产网站,这尤其重要,因为不能完全访问纯CSS工具提示

The information that you want to show can be stored in a data-tooltip attribute.

您想要显示的信息可以存储在data-tooltip属性中。

<span data-tooltip="A simple explanation">Word</span>

You can then present the data to the user with the ::before pseudo element.

然后,您可以使用::before伪元素将数据呈现给用户。

span::before {
  content: attr(data-tooltip);
  // More Style Rules
}

span:hover::before {
  display: inline-block;
}

See the Pen Creating tooltips with data attributes by SitePoint (@SitePoint) on CodePen.

请参阅CodePen具有 SitePoint( @SitePoint )的数据属性的笔创建工具提示

使用JavaScript访问数据属性 (Accessing Data Attributes with JavaScript)

There are three ways of accessing data attributes in JavaScript.

有3种方法可以访问JavaScript中的数据属性。

使用getAttribute和setAttribute (Using getAttribute and setAttribute)

You can use getAttribute() and setAttribute() in JavaScript to get and set the value of different data attributes.

您可以在JavaScript中使用getAttribute()setAttribute()来获取和设置不同数据属性的值。

The getAttribute method will either return null or an empty string if the given attribute does not exist. Here is an example of using these methods:

如果给定属性不存在,则getAttribute方法将返回null或空字符串。 这是使用这些方法的示例:

var restaurant = document.getElementById("restaurantId");
var ratings = restaurant.getAttribute("data-ratings");

You can use the setAttribute method to modify the value of existing attributes or to add new attributes.

您可以使用setAttribute方法来修改现有属性的值或添加新属性。

restaurant.setAttribute("data-owner-name", "someName");

使用数据集属性 (Using the dataset Property)

A simpler method of accessing data attributes is with the help of the dataset property. This property returns a DOMStringMap object with one entry for each custom data attribute.

访问数据属性的一种更简单的方法是借助dataset属性。 此属性返回一个DOMStringMap对象,其中每个自定义数据属性都有一个条目。

There are a few things that you should keep in mind while using the dataset property.

使用dataset属性时,应牢记一些注意事项。

It takes three steps to transform a custom data attribute into a DOMStringMap key:

将自定义数据属性转换为DOMStringMap密钥需要三个步骤:

  • The data- prefix is removed from the attribute name

    data-前缀已从属性名称中删除

  • Any hyphen followed by a lower case letter is removed from the name and the letter following it is converted to uppercase

    名称中删除所有后跟小写字母的连字符,并将其后的字母转换为大写
  • Other characters will remain unchanged. This means that any hyphen that is not followed by a lowercase letter will also remain unchanged.

    其他字符将保持不变。 这意味着任何不带小写字母的连字符也将保持不变。

The attributes can then be accessed using the camelCase name stored in the object as a key like element.dataset.keyname.

然后可以使用存储在对象中的camelCase名称作为诸如element.dataset.keyname类的键来访问属性。

Another way of accessing the attributes is using bracket notation, like element.dataset[keyname]

访问属性的另一种方法是使用括号表示法,例如element.dataset[keyname]

Consider the following HTML:

考虑以下HTML:

<li data-type="veg" data-distance="2miles" data-identifier="10318" data-owner-name="someName">
  Salad King
</li>

Here are a few examples:

这里有一些例子:

var restaurant = document.getElementById("restaurantId");

var ratings = restaurant.dataset.ratings;
restaurant.dataset.ratings = newRating;

var owner = restaurant.dataset['ownerName'];
restaurant.dataset['ownerName'] = 'newOwner';

This method is now supported in all major browsers and you should favor it over the previous method for accessing custom data attributes.

现在,所有主流浏览器都支持此方法并且您应该比以前的方法更喜欢它来访问自定义数据属性。

使用jQuery (Using jQuery)

You can also use the jQuery data() method to access data attributes of an element. Before jQuery version 1.6, you had to use the following code to access data attributes:

您还可以使用jQuery data()方法访问元素的数据属性。 在jQuery 1.6版之前,您必须使用以下代码访问数据属性:

var restaurant = $("#restaurantId");

var owner = restaurant.data("owner-name");
restaurant.data("owner-name", "newName");

From version 1.6, jQuery started using the camelCase version of data attributes. Now, you can do the same thing using the following code:

从1.6版开始,jQuery开始使用camelCase版本的数据属性。 现在,您可以使用以下代码执行相同的操作:

var restaurant = $("#restaurantId");

var owner = restaurant.data("ownerName");
restaurant.data("ownerName", "newName");

You should know that jQuery also tries to internally convert the string obtained from a data attribute into a suitable type like numbers, booleans, objects, arrays and null.

您应该知道jQuery还尝试将从data属性获得的字符串内部转换为合适的类型,例如数字,布尔值,对象,数组和null。

var restaurant = $("#restaurantId");
var identifier = restaurant.data("identifier");

console.log(typeof identifier);
// number

If you want jQuery to get the value of an attribute as a string without any attempt to convert it into other types, you should use jQuery’s attr() method.

如果希望jQuery以字符串形式获取属性值而不尝试将其转换为其他类型,则应使用jQuery的attr()方法

jQuery only retrieves the value of data attributes the first time they are accessed. The data attributes are then no longer accessed or changed. All the changes that you make to those attributes are made internally and accessible only within jQuery.

jQuery仅在首次访问数据属性时才检索它们的值。 这样就不再访问或更改数据属性。 您对这些属性所做的所有更改都是在内部进行的,并且只能在jQuery中访问。

Let’s assume you are manipulating the data attributes of the following list item:

假设您正在操纵以下列表项的数据属性:

<li id="salad" data-type="veg" data-distance="2miles" data-identifier="10318">
  Salad King
</li>

You can use the code below to change the value of its data-distance attribute:

您可以使用下面的代码来更改其data-distance属性的值:

var distance = $("#salad").data("distance");
console.log(distance);
// "2miles"

$("#salad").data("distance","1.5miles");
console.log(distance);
// "1.5miles"

document.getElementById("salad").dataset.distance; 
// "2miles"

As you can see, accessing the value of the data-distance attribute using vanilla JavaScript (not jQuery) keeps giving us the old result.

如您所见,使用普通JavaScript(而非jQuery)访问data-distance属性的值将始终为我们提供旧的结果。

结论 (Conclusion)

In this tutorial I have covered all the important things that you need to know about HTML5 data attributes. Besides creating tooltips and styling elements using attribute selectors, you can use data attributes to store and show users some other data like a notification about unread messages and so on.

在本教程中,我介绍了您需要了解的有关HTML5数据属性的所有重要内容。 除了使用属性选择器创建工具提示和样式元素外,您还可以使用数据属性来存储和向用户显示一些其他数据,例如有关未读消息的通知等。

If you have any other questions about data attributes, let me know in the comments.

如果您对数据属性还有其他疑问,请在评论中告诉我。

翻译自: https://www.sitepoint.com/how-why-use-html5-custom-data-attributes/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值