官术网_书友最值得收藏!

Assigning custom data attributes

With HTML5, we now have the ability to assign custom data attributes to any HTML5 element. The W3C defines it as:

Attribute that is intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

These new custom data attributes consist of two parts:

  • Attribute name: It must start with the prefix data- and should be followed with at least one character and should not contain uppercase characters
  • Attribute value: It must be a string value

Let's add a custom attribute to a <div> tag as shown in the following code:

<div id="bookList" data-category="TechnicalBooks">
Developing for windows 8
</div>

You can see the custom attribute name data-category and the attribute value TechnicalBooks assigned to the <div> element. This data can be retrieved and updated by your JavaScript code using the native getAttribute and setAttribute methods, because the custom data attributes are considered to be part of the page on which they are used. The following is the code sample that shows how to manipulate the custom attributes using native JavaScript:

function getSetCategory() {
  var bookList = document.getElementById("bookList");
//get the value of the attribute
  var bookCategory = bookList.getAttribute('data-category');
//set the value for the attribute
  bookList.setAttribute('data-category', 'HealthBooks');
//remove the attribute
  bookList.removeAttribute('data-category');
}

The HTML5 specification clearly states that the data attributes should not be used to replace an existing attribute or an element that may be more semantically appropriate. For example, it would be inappropriate to add a data-time attribute to specify a time value in a span element as the following code shows:

<span data-time="08:00">8am<span>

The most appropriate and more semantic element to use would be a time element, as the following code shows:

<time datetime="08:00">8am</time>

When developing Windows 8 apps, we can use the Windows library for JavaScript (WinJS) to achieve more advanced binding of data to HTML elements. The Win8 JavaScript library utilizes the HTML data-* attributes to provide an easy way to programmatically implement data binding.

主站蜘蛛池模板: 永新县| 香格里拉县| 盐源县| 永济市| 扶风县| 密山市| 平果县| 抚顺市| 蒲江县| 敖汉旗| 阜平县| 铁岭市| 平邑县| 阿拉善盟| 栖霞市| 诸暨市| 金门县| 正定县| 霸州市| 承德县| 黄骅市| 诸城市| 卢湾区| 佛教| 柯坪县| 砀山县| 鄂尔多斯市| 吴旗县| 汝南县| 无极县| 北碚区| 乌拉特前旗| 利辛县| 巴中市| 镇宁| 勃利县| 酉阳| 赤峰市| 扶沟县| 桂平市| 宣威市|