HTML5 的自定义 data-* 属性和jquery的data()方法的使用
人们总喜欢往HTML标签上添加自定义属性来存储和操作数据。但这样做的问题是,你不知道将来会不会有其它脚本把你的自定义属性给重置掉,此外,你这样做也会导致html语法上不符合Html规范,以及一些其它副作用。这就是为什么在HTML5规范里增加了一个自定义data属性,你可以拿它做很多有用的事情。
你可以去读一下HTML5的详细规范,但这个自定义data属性的用法非常的简单,就是你可以往HTML标签上添加任意以 "data-"开头的属性,这些属性页面上是不显示的,它不会影响到你的页面布局和风格,但它却是可读可写的。
下面的一个代码片段是一个有效的HTML5标记:
<p id="awesome" data-myid="3e4ae6c4e">Some awesome data</p>
可是,怎么来读取这些数据呢?你当然可以遍历页面元素来读取你想要的属性,但jquery已经内置了方法来操作这些属性。使用jQuery的.data()方法来访问这些"data-*" 属性。其中一个方法就是 .data(obj),这个方法是在 jQuery1.4.3版本后出现的,它能返回相应的data属性。
举个例子,你可以用下面的写法读取 data-myid属性值:
var myid= jQuery("#awesome").data('myid'); console.log(myid);
你还可以在"data-*" 属性里使用json语法,例如,如果你写出下面的html:
<p id="awesome-json" data-awesome='{"game":"on"}'></p>
你可以通过js直接访问这个数据,通过json的key值,你能得到相应的value:
var gameStatus= jQuery("#awesome-json").data('awesome').game; console.log(gameStatus);
你也可以通过.data(key,value)方法直接给"data-*" 属性赋值。一个重要的你要注意的事情是,这些"data-*" 属性应该和它所在的元素有一定的关联,不要把它当成存放任意东西的存储工具。
补充:尽管"data-*" 是HTML5才出现的属性,但jquery是通用的,所以,在非HTML5的页面或浏览器里,你仍然可以使用.data(obj)方法来操作"data-*" 数据
以上就是HTML5 的自定义 data-* 属性和jquery的data()方法的使用的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.
