jQuery map函数将jQuery对象中的一组元素转换为jQuery数组中可能包含或不包含元素的另一组值。该grep()函数用于查找数组的元素。区别在于我们使用$.grep过滤数组,并使用$.map将函数应用于数组中的每个项目。
jQuery map函数
map方法将jQuery对象中的一组元素转换为jQuery数组中可能包含或不包含元素的另一组值。
以下是jQuery.map()方法的参数:
callback-在集合中的每个元素上执行的函数。
您可以尝试运行以下代码来学习如何使用jQuery.map()方法:
<html>
<head>
<title>jQuery Map Method</title>
<script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var mappedItems = $("li").map(function (index) {
var replacement = $("<li>").text($(this).text()).get(0);
if (index == 0) {
//使第一个项目全部大写
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
//删除第二和第四项
replacement = null;
} else if (index == 2) {
//在第三项中添加两项,并添加一些文本
replacement = [replacement,$("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
//替换将是一个dom元素,为null,
//或dom元素数组
return replacement;
});
$("#results").append(mappedItems);
});
</script>
<style>
body {
font-size:18px;
}
ul {
float:left;
margin:0 30px;
color:green;
}
#results {
color:blue;
}
</style>
</head>
<body>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
<ul id = "results">
</ul>
</body>
</html>jQuery grep函数
该grep()函数用于查找数组的元素。
您可以尝试运行以下代码来学习如何使用grep():
<html>
<head>
<title>jQuery grep() function</title>
<style>
div {
color: blue;
}
p {
color: red;
margin: 0;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<p></p>
<script>
var arr1 = [ 1, 7, 4, 8, 6, 1, 9, 5, 3, 7, 3, 8, 5, 8, 2 ];
$( "div" ).text( arr1.join( ", " ) );
arr1 = jQuery.grep(arr1, function( n, i ) {
return ( n !== 5 && i > 6 );
});
$( "p" ).text( arr1.join( ", " ) );
</script>
</body>
</html>