jquery stores data in elements: data()

无忌哥哥
Release: 2018-06-29 13:39:50
Original
1942 people have browsed it

Storing data in elements: data()

    3.在元素中存储数据:data() 
php中文网
Copy after login

data(): Read custom data whose attribute name starts with data- in the element, you can omit the data- prefix

var res = $('#pic').data('job')
Copy after login

If you use the previous attr() method, you must write the complete attribute name

var res = $('#pic').attr('data-job')
Copy after login

data() is also a method with its own reader and setter

$('#pic').data('data-course', 'php项目开发课程')
Copy after login

If it is dynamically set automatically Defining attributes cannot be obtained if you omit the prefix

var res = $('#pic').data('course')
Copy after login

You need to add the prefix

var res = $('#pic').data('data-course')
Copy after login

Can data() obtain the native attributes on the element? Unable to read

var res = $('#pic').data('title')
Copy after login
Copy after login

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')
Copy after login

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')
Copy after login
Copy after login

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') //仅删除临时创建的
Copy after login

The custom attributes that come with the original tag cannot be deleted.

var res = $('#pic').removeData('data-job') var res = $('#pic').data('job')
Copy after login

View the results in the console

console.log(res)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!