1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!doctype html>
<html>
<head>
     <meta charset= "UTF-8" >
     <title>返回值:jQuerydata([key],[value])</title>
</head>
<body>
     <!-- demo3 data方法的使用 -->
     <a href= "javascript:;"  id= "demo3" >demo3</a>
     <div></div>
     <button id= "clear" >clear</button>
     <script type= "text/javascript"  src= "http://lib.sinaapp.com/js/jquery/1.8.3/jquery.min.js" ></script>
     <script type= "text/javascript" >
         /**
          *返回值:jQuerydata([key],[value])
          *key:存储的数据名
          *value:将要存储的任意数据
          *
          *在元素上存放数据,返回jQuery对象。
          *V1.4.3 新增用法NEW data(obj) 可传入key-value形式的数据。
          *
          */
         $(document).ready( function (){
             /**
              * demo3
              */
             $( "#demo3" ).click( function (){
                 //赋值
                 $( this ).data( "value" , "hanchao" );
                 //取值
                 var  value = $( this ).data( "value" );
                 console.log(value);
                 //重新赋值
                 $( this ).data( "value" ,78);
                 //重新取值
                 var  value_new = $( this ).data( "value" );
                 console.log(value_new);
                 //赋值一个对象
                 $( this ).data( "user" ,{username: "tom" ,password: "123456" ,address: "China" });
                 //取值
                 var  username = $( this ).data( "user" ).username;
                 var  password = $( this ).data( "user" ).password;
                 var  address = $( this ).data( "user" ).address;
                 console.log( "username:"  + username +  ", password:"  + password +  ", address:"  + address);
                 //我们还可以把值放在一个div中
                 $( "div" ).data( "test" ,{username: "tom" ,password: "123456" ,address: "China" });
                 //取值
                 var  username1 = $( "div" ).data( "test" ).username;
                 var  password1 = $( "div" ).data( "test" ).password;
                 var  address1 = $( "div" ).data( "test" ).address;
                 console.log( "username1:"  + username1 +  ", password1:"  + password1 +  ", address1:"  + address1);
             });
             /**
              * [ description] 清除div中的data数据
              * @return {[type]}
              */
             $( "#clear" ).click( function (){
                 $( "div" ).removeData( "test" );
                 //取值
                 var  username = $( "div" ).data( "test" );
                 console.log( "username1:"  + username);
             });
         });
     </script>
</body>
</html>