Home > Web Front-end > JS Tutorial > body text

jquery stores data in elements: data()

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

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

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

var res = $(&#39;#pic&#39;).data(&#39;job&#39;)
Copy after login

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

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

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

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

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

var res = $(&#39;#pic&#39;).data(&#39;course&#39;)
Copy after login

You need to add the prefix

var res = $(&#39;#pic&#39;).data(&#39;data-course&#39;)
Copy after login

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

var res = $(&#39;#pic&#39;).data(&#39;title&#39;)
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 = $(&#39;#pic&#39;).data(&#39;title&#39;,&#39;hellow&#39;)
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 = $(&#39;#pic&#39;).data(&#39;title&#39;)
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 = $(&#39;#pic&#39;).data(&#39;data-course&#39;)  //仅删除临时创建的
Copy after login

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

var res = $('#pic').removeData('data-job') 
var res = $(&#39;#pic&#39;).data(&#39;job&#39;)
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template