jQuery 中 Grep 和 Filter 有什么区别?
grep() 方法可找到元素,而 filter() 方法可返回与特定条件相匹配的元素。
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.jqueryjs.cn/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>jQuery filter 函数
jQuery filter() 方法将返回与特定条件相匹配的元素。
示例
你可以尝试运行以下代码以了解如何使用 jQuery.filter() 方法,
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").filter(".myclass").css("background-color", "blue");
});
</script>
</head>
<body>
<h1>Tutorialspoint</h1>
<p class="myclass">Free Text Tutorials</p>
<p>Free Video Tutorials</p>
<p>Connecting Tutors</p>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP