Home >Web Front-end >JS Tutorial >jquery stores data in elements: data()

jquery stores data in elements: data()

无忌哥哥
无忌哥哥Original
2018-06-29 13:39:502053browse

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 = $(&#39;#pic&#39;).data(&#39;job&#39;)

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

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

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

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

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;)

You need to add the prefix

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

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

var res = $(&#39;#pic&#39;).data(&#39;title&#39;)

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;)

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;)

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;)  //仅删除临时创建的

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;)

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!

Statement:
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