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


Build a list of all the values within a form.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>map demo</title>
<style>
p {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><b>Values: </b></p>
<form>
<input type="text" name="name" value="John">
<input type="text" name="password" value="password">
<input type="text" name="url" value="http://ejohn.org/">
</form>
<script>
$( "p" )
.append( $( "input" ).map(function() {
return $( this ).val();
})
.get()
.join( ", " ) );
</script>
</body>
</html>

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

A contrived example to show some functionality.

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>map demo</title>
<style>
body {
font-size: 16px;
}
ul {
float: left;
margin: 0 30px;
color: blue;
}
#results {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
<ul id="results">
</ul>
<script>
var mappedItems = $( "li" ).map(function( index ) {
var replacement = $( "<li>" ).text( $( this ).text() ).get( 0 );
if ( index === 0 ) {
// Make the first item all caps
$( replacement ).text( $( replacement ).text().toUpperCase() );
} else if ( index === 1 || index === 3 ) {
// Delete the second and fourth items
replacement = null;
} else if ( index === 2 ) {
// Make two of the third item and add some text
replacement = [ replacement, $( "<li>" ).get( 0 ) ];
$( replacement[ 0 ] ).append( "<b> - A</b>" );
$( replacement[ 1 ] ).append( "Extra <b> - B</b>" );
}
// Replacement will be a dom element, null,
// or an array of dom elements
return replacement;
});
$( "#results" ).append( mappedItems );
</script>
</body>
</html>

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

Equalize the heights of the divs.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>map demo</title>
<style>
div {
width: 40px;
float: left;
}
input {
clear: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input type="button" value="equalize div heights">
<div style="background: red; height: 40px; "></div>
<div style="background: green; height: 70px;"></div>
<div style="background: blue; height: 50px; "></div>
<script>
$.fn.equalizeHeights = function() {
var maxHeight = this.map(function( i, e ) {
return $( e ).height();
}).get();
return this.height( Math.max.apply( this, maxHeight ) );
};
$( "input" ).click(function() {
$( "div" ).equalizeHeights();
});
</script>
</body>
</html>

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