JS Data hook HTML5 dataset__js

Source: Internet
Author: User

The practice of data-* hooks is now popular. Famous since HTML5.

When writing HTML code, it is often necessary to reserve data hooks for JS in the DOM structure, and these hooks are usually implemented in this way:

<div id= "test" url= "http://www.mangguo.org" > Mango station </div>
HTML5 better regulate the way it is used:

<div id= "test" data-url= "http://www.mangguo.org" > Mango station </div>
The way to get custom data properties is consistent:

document.getElementById (' Test '). getattribute (' Data-url ');
In a real-world scenario, custom attributes are usually multiple simultaneous, and then there are several ways to do this:

<div id= "test" data-url= "http://www.mangguo.org" data-author= "Tinyhill" > Mango station </div>
<div id= "Test" data-config= "{' URL ': ' http://www.mangguo.org ', ' Author ': ' Tinyhill '}" > Mango station </div>
If this is the second type of writing, usually through eval or json.parse to parse it into a JS literal object, but often because of the single quotation mark double quotes problems appear various traps.

For the first type of writing that follows the HTML5 standard, the advanced browser has already supported the DataSet, namely:

document.getElementById (' Test '). DataSet;
The execution result is an object of type Domstringmap:

{URL: "http://www.mangguo.org", Author: "Tinyhill"}

--------------------------------------------------------------------------------------------------------------- ----- HTML5 Custom Property Object DataSet Introduction First, HTML5 custom properties Introduction

Previously translated "You Must know 28 HTML5 features, tips and techniques" in the article for HTML5 Custom legal attributes data-has been introduced, that is, in HTML5 we can use the data-prefix to set the custom attributes we need to do some data storage, For example, we want to store the corresponding ID on a text button:

<a href= "javascript:" data-id= "2312" > Test </a>

The data-prefix here is called the Data property, which can be defined by scripting or can be styled using the CSS property selector. The quantity is unrestricted and provides very powerful control over the control and rendering of data. Ii. The base of the dataset

The following is an example of an element applying the Data property:

<div id= "Day2-meal-expense" data-drink= "coffee" data-food= "Sushi"
  data-meal= "Lunch" >¥20.12 </div>

To get the value of a property, you can use the DataSet object as follows:

var expenseday2 = document.getElementById (' day2-meal-expense ');
var typeofdrink = Expenseday2.dataset.drink;

About this basic use, I made a demo, you can ruthlessly click here: DataSet Basic Use instance Demo

Click on the Demo page button to do the test, if the browser does not support the dataset, such as Firefox 4, the pop-up results will be similar to the following:

If supported, such as the Chrome 11 browser, the pop-up results are:

It should be noted that the name of a hyphen connection needs to be named as a camel when used, that is, a combination of uppercase and lowercase, similar to the style object of the applied element, Dom.style.borderColor. For example, suppose that the above example now has the following data property, Data-meal-time, we want to get the corresponding value can use:

Expenseday2.dataset.mealTime

The Data property is basically supported by all browsers, but the DataSet object belongs to the upstart, currently only in opera 11.1+, Chrome 9+ can use the dataset to access your custom data properties through JavaScript. As for other browsers, FireFox 6+ (not out) and Safari 6+ (not out) will support the DataSet object, as for IE browser, it seems to be a distant trend. Specific compatibility data, you can click here to visit. Third, why do we need a dataset

If you use a traditional method to get a property value, it should look like this:

var typeofdrink = document.getElementById (' Day2-meal-expense '). getattribute (' Data-drink ');

Now, let's say we're going to get multiple custom attribute values, so the toss is coming, and we're probably going to implement the following N-line code like this:

var attrs = expenseday2.attributes,
expense = {}, I, J;
for (i = 0, j = attrs.length I < J; i++) {
  if (attrs[i].name.substring (0, 5) = = ' data-') {
    Expense[attrs[i].nam E.substring (5)] = Attrs[i].value
  }
}

and using the DataSet attribute, we don't need any loops to get the value you want, just the second kill:

Expense = document.getElementById (' Day2-meal-expense '). DataSet;

The dataset is not a typical JavaScript object, but rather a Domstringmap object, Domstringmap is HTML5 a new interaction variable that contains multiple name-value pairs. Iv. operation of the dataset

You can manipulate name-value pairs as follows:

Chartinput = [];
For (var item in expense) {
  Chartinput.push (Expense[item]);
}

The line of code above is to have all the custom attribute values crammed into an array.

If you want to delete a data property, you can do this:

Delete expenseday2.dataset.meal;

If you want to add an attribute to an element, you can do so:

Expenseday2.dataset.dessert = ' icecream ';
v. the speed compared with getattribute

Using dataset to manipulate data is a bit slower than using getattribute, and here's a page that tests the speed of both methods, dataset vs attributes loop, using the Chrome browser and the opera 11.1+ browser, When you click the Run Test button, you will get some data, the following screenshot:

However, if we are only dealing with a small amount of data, the effect of this difference in speed is basically not there. Instead, we should see that using a dataset to manipulate adaptive properties is a lot less annoying and more readable than other getattribute forms. So, on balance, the operation of custom attributes, the dataset operation is the election. Vi. where to use datasets

Each time you use a custom data attribute, using the dataset to get name-value pairs is a good choice. In view of the fact that many browsers still treat the DataSet as an alien alien, it is necessary, in practical use, to perform a feature check to see if the dataset is supported, similar to the following:

if (expenseday2.dataset) {
  Expenseday2.dataset.dessert = ' icecream ';
} else {
  expenseday2.setattribute (' Data-dessert ', ' icecream ');

Note: If your application updates the Data property values frequently, it is recommended that you use JavaScript objects to manage it instead of updating it every time through the Data property. the data attribute in CSS

We can set the CSS style for the corresponding element based on the data property value, such as the following example:

The HTML code is as follows:

<div class= "MM" Data-name= "Zhang contains rhyme" ></div>
<div class= "mm" data-name= "undefined" ></div>

The CSS code is as follows:

. mm{width:256px; height:200px;}
. Mm[data-name= ' Zhang Yun ']{background:url (http://image.zhangxinxu.com/image/study/s/s256/mm1.jpg) no-repeat;
Mm[data-name= ' undefined ']{background:url (http://image.zhangxinxu.com/image/study/s/s256/mm3.jpg) no-repeat;

The result is a picture of a beautiful woman and a big girl, such as the screenshot below in IE7 document mode:

You can ruthlessly click here: HTML5 custom properties and CSS3 style demo Eight, a simple comprehensive example

To show the dataset's application, here is a demo page, if you use DataSet to make the data graph effect, you can ruthlessly click here: HTML5 DataSet under the data map demo

Sliding the HTML5 range control, you can see the following data and the size of the graphic changed, as the following screenshot (truncated from opera 11.1):
Ix. Conclusion

It is a good idea to use the dataset to get the custom attributes of an element, and with more and more browser support, such as the Firefox browser, this object attribute is likely to be used formally in the actual project. Although using a dataset does not improve the performance of your code, it can be helpful to improve the readability and maintainability of your code for simple code.

If you are interested in DataSet, do some demo or something, you can go here Opera Github repository play your little achievements.

Reference article: an Introduction to datasets
Demo support: Cost of electricity€/kwh over the decade

Turn from: http://www.zhangxinxu.com/wordpress/?p=1693

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.