Operate dataattributes in HTML5 in jquery

Source: Internet
Author: User

In HTML5, the data-attributes attribute is added. You can save some data at the page level, for example:
Java code
1. <body>
2. <div data-site = "www.codeguru.com" data-category = "Technology"> Hi, Welcome to HTML 5 data attributes! </Div>
3.
4. <div data-name = "Dave" data-age = 23 data-dept = "Clerical"> Hi Dave! </Div>
5. </body>
6.


In jquery, you can use the. data method to obtain and set data attributes, for example:
Java code
1. <! DOCTYPE html>
2. 3. 4. <title> Untitled Page </title> 5.
5. <script type = "text/javascript">
6. $ ("# btnSet"). click (function (e ){
7. $ ("# divEmployee"). data ("name", "Dave ");
8. $ ("# divEmployee"). data ("age", "23 ");
9. $ ("# divEmployee"). data ("dept", "Clerical ");
10. 10.
11.}); </script>
12. 13. <body>
14. <div id = "divEmployee">
15. Hi Dave!
16. </div>
17. 15.
18. <input type = "button" id = "btnSet" value = "Set Value"/>
19. </body>
20.

We can see a series of divEmployee attributes, including name, age, and dept.

You can also set it using the following two methods:
Java code
1. <script type = "text/javascript">
2. $ ("# btnSet"). click (function (e ){
3. $ ("# divEmployee"). data ({
4. "name": "Dave ",
5. "age": 23,
6. "dept": "Clerical"
7 .});
8 .});
9. </script>
10.
11.

 


Java code
1. <script type = "text/javascript">
2. $ ("# btnSet"). click (function (e ){
3. $ ("# divEmployee"). data ("name", "age", "dept"). data ("Dave", 23, "Clerical ");
4 .});
5. </script>

 

The methods for obtaining and deleting are as follows:
Java code
1.
2. <script type = "text/javascript">
3. $ ("# btnSet"). click (function (e ){
4. var name = $ ("# divEmployee"). data ("name ")
5. var age = $ ("# divEmployee"). data ("age ")
6. var dept = $ ("# divEmployee"). data ("dept ")
7 .});
8. </script>



Java code
1.
2. <script type = "text/javascript">
3. $ ("# btnSet"). click (function (e ){
4. $ ("# divEmployee"). removeData ("employee ");
5.}); </script>

 


From jackyrong

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.