Home > Article > Web Front-end > Interaction between data-* and js
This time I will bring you the interaction between data-* and js. What are the precautions for the interaction between data-* and js? The following is a practical case, let's take a look.
HTML5New Attributedata-*
Writing Example<p data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'> </p>
1. Definition:
data-* attributes are used to store private custom data for a page or application. data-* attributes give us the ability to embed custom data attributes on all HTML elements.2. Note:
data-* attribute consists of two parts:data-* attribute and jQueryInteraction
Use the .data() function in jQuery to get the data-* attribute valueconsole.log($("p").data('lastValue')); //输出的值为:43 console.log($("p").data('role')); //输出的值为:page
Note
data-**Attribute name format camel case naming rewritingdata-attribute is the first time After using this data attribute, there is no need to access or change it (all data values are stored internally in jQuery) Demo:
console.log($("p").data('lastValue')); //输出的值为:43 $('p').data('lastValue',44); //设置data-last-value=44 $('p')[2] //假设这是文档中的第3个p,我们输出这个dom //输出:<p data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'>Don’t be afraid, you can output it again
console.log($("p").data('lastValue')); //输出的值为:44The value is just stored inside jQueryUse the .attr() function in jQuery to get the data-* attribute value
console.log($('p').attr('data-role')); //输出的值为:page console.log($('p').attr('data-last-value')); //输出的值为:43Use the .attr() function in jQuery to set the data-* Attribute value
$('p').attr('data-emp',{'name':'zhangsan','age':23}); //给p添加一个data-emp的属性,属性值为一个json对象Note: dashes should be converted into camel case naming
I believe you have mastered the method after reading the case in this article, please come for more exciting information Pay attention to other related articles on php Chinese website! Recommended reading:
Detailed explanation of H5 server push events
Realizing mobile animation effects based on HTML5 gyroscope
H5 canvas implements the Snake game
The above is the detailed content of Interaction between data-* and js. For more information, please follow other related articles on the PHP Chinese website!