Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery filter()

jQuery filter()

filter()方法返回与指定条件匹配的元素。如果元素不符合条件,则将其从选择中删除。
可能需要 选择器 功能 作为其参数来过滤匹配的元素集。使用 选择器 时,该方法会过滤与指定选择器不匹配的元素。如果我们使用 function ,则该方法会过滤与给定功能不匹配的元素。通常,此方法用于减少对所选元素集中的元素的搜索。

语法

使用 selector
$(selector).filter(selector)
使用功能
$(selector).filter(function(index))
此函数的参数值定义如下。
选择器: 。它是一个可选属性。它可以是 JQuery 对象或选择器表达式。我们还可以使用逗号分隔的表达式列表来一次应用多个过滤器。可以这样写:
filter("id1, #id2")
功能: 它也是可选参数。此参数指定为组中的每个元素运行的函数。如果函数返回true,则保留该元素。否则,返回false时,将删除该元素。
index 参数表示该元素在集合中的位置。它从 0 位置开始。
让我们看一些示例,以了解如何使用 filter()方法。
示例1
在此示例中,我们使用 filter()函数的 selector 属性。在这里, filter()函数返回类名称为 para 的所有段落元素。有一些div元素,段落元素等。与类别 para 相关的四个段落元素中有三个。
我们必须单击给定的按钮才能看到结果。
<!DOCTYPE html>
<html>
<head>
<style>
div{
font-size: 20px;
font-weight: bold;
}
</style>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
  $("p").filter(".para").css({"background": "yellow"});
});
}
</script>
</head>
<body>
<h2> Welcome to the lidihuo.com </h2>
<h4>This is an example of using the jQuery's filter() method. </h4>
  <div id = "div1"> This is first div element. </div>
          <p class = "para"> This is first paragraph element </p>
<div id = "div2"> This is second div element. </div>
<p class = "para"> This is second paragraph element </p>
<p class = "para"> This is third paragraph element </p>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()"> click me </button>
  </body>
</html>
输出

Welcome to the lidihuo.com

This is an example of using the jQuery's filter() method.

This is first div element.

This is first paragraph element

This is second div element.

This is second paragraph element

This is third paragraph element

Click the following button to see the effect.

Example2

在此示例中,我们使用了 function(index) 参数filter()函数。在此处,该函数突出显示索引位置为 1、3, 5 的段落元素。由于索引以 0 开头,因此该段落突出显示了偶数位置。
<!DOCTYPE html>
<html>
<head>
<style>
p{
font-size: 20px;
font-weight: bold;
}
</style>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
  $("p").filter(function(index) {
  if(index == 1 || index == 3 || index == 5){
  return true;
  }
  }).css({"background": "yellow"});
});
}
</script>
</head>
<body>
<h2> Welcome to the lidihuo.com </h2>
<h4> This is an example of using the jQuery's filter() method. </h4>
  <p class = "para1"> P1 </p>
          <p class = "para2"> P2 </p>
<p class = "para3"> P3 </p>
<p class = "para4"> P4 </p>
<p class = "para5"> P5</p>
<p class = "para6"> P6 Click the following button to see the effect. </p>
<button onclick = "fun()"> click me </button>
  </body>
</html>
输出

Welcome to the lidihuo.com

This is an example of using the jQuery's filter() method.

P1

P2

P3

P4

P5

P6 Click the following button to see the effect.

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4