Storing data in elements: data()
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>3.在元素中存储数据:data()</title> </head> <body> <img src="../images/peter.jpg" width="200" alt="php中文网" title="朱老师" id="pic" data-job="php中文网朱老师"> </body> </html>
data(): Read custom data whose attribute name starts with data- in the element, you can omit the data- prefix
var res = $('#pic').data('job')
If you use the previous attr() method, you must write the complete attribute name
var res = $('#pic').attr('data-job')
data() is also a method with its own reader and setter
$('#pic').data('data-course', 'php项目开发课程')
If it is dynamically set automatically Defining attributes cannot be obtained if you omit the prefix
var res = $('#pic').data('course')
You need to add the prefix
var res = $('#pic').data('data-course')
Can data() obtain the native attributes on the element? Unable to read
var res = $('#pic').data('title')
However, it supports dynamically setting the title attribute, which is limited to use in scripts. The original value has not changed.
var res = $('#pic').data('title','hellow')
Now you can read the value of title in the script, although this value is different from the native alt value. Same
var res = $('#pic').data('title')
Similarly, data() also has a corresponding removeData() used to delete custom attributes or attributes created by it
var res = $('#pic').removeData('title') //仅删除临时创建的,原值不受影响 var res = $('#pic').removeData('data-course') //仅删除临时创建的 var res = $('#pic').data('data-course') //仅删除临时创建的
The custom attributes that come with the original tag cannot be deleted.
var res = $('#pic').removeData('data-job') var res = $('#pic').data('job')
View the results in the console
console.log(res)
The above is the detailed content of jquery stores data in elements: data(). For more information, please follow other related articles on the PHP Chinese website!