Примеры для jQuery.data()


Store then retrieve a value from the div element.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.data demo</title>
<style>
div {
color: blue;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>
The values stored were
<span></span>
and
<span></span>
</div>
<script>
var div = $( "div" )[ 0 ];
jQuery.data( div, "test", {
first: 16,
last: "pizza!"
});
$( "span:first" ).text( jQuery.data( div, "test" ).first );
$( "span:last" ).text( jQuery.data( div, "test" ).last );
</script>
</body>
</html>

Демонстрация:

Get the data named "blah" stored at for an element.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.data demo</title>
<style>
div {
margin: 5px;
background: yellow;
}
button {
margin: 5px;
font-size: 14px;
}
p {
margin: 5px;
color: blue;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>A div</div>
<button>Get "blah" from the div</button>
<button>Set "blah" to "hello"</button>
<button>Set "blah" to 86</button>
<button>Remove "blah" from the div</button>
<p>The "blah" value of this div is <span>?</span></p>
<script>
$( "button" ).click( function() {
var value,
div = $( "div" )[ 0 ];
switch ( $( "button" ).index( this ) ) {
case 0 :
value = jQuery.data( div, "blah" );
break;
case 1 :
jQuery.data( div, "blah", "hello" );
value = "Stored!";
break;
case 2 :
jQuery.data( div, "blah", 86 );
value = "Stored!";
break;
case 3 :
jQuery.removeData( div, "blah" );
value = "Removed!";
break;
}
$( "span" ).text( "" + value );
});
</script>
</body>
</html>

Демонстрация: