📜  jQuery filter()

📅  最后修改于: 2020-11-27 00:53:46             🧑  作者: Mango

jQuery filter()

filter()方法返回与指定条件匹配的元素。如果元素不符合条件,则将其从选择中删除。

它可以将选择器或函数作为其参数,以过滤匹配的元素集。使用选择器时,该方法过滤的元素与给定的选择器不匹配。如果我们使用函数,该方法将过滤与给定函数不匹配的元素。通常,此方法用于减少对所选元素集中的元素的搜索。

句法

使用选择器

$(selector).filter(selector)

使用函数

$(selector).filter(function(index))

该函数的参数值定义如下。

选择器:这是一个可选属性。它可以是JQuery对象或选择器表达式。我们还可以使用逗号分隔的表达式列表来一次应用多个过滤器。可以这样写:

filter("id1, #id2")

函数:也是可选参数。此参数指定为组中的每个元素运行的函数。如果函数返回true,则保留该元素。否则,返回false时,将删除该元素。

index参数表示元素在集合中的位置。它从0位置开始。

让我们看一些示例,以了解如何使用filter()方法。

例1

在此示例中,我们使用filter()函数的选择器属性。在这里,filter()函数返回所有具有类名称para的段落元素。有一些div元素,段落元素等。在与class para有关的四个段落中,有三个段落元素。

我们必须单击给定的按钮以查看结果。









 

Welcome to the javaTpoint.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.

输出量

单击按钮后,我们可以看到该函数返回了与类名para相关的段落元素。

例2

在此示例中,我们使用filter()函数的函数(索引)参数。.在此,该函数突出显示索引位置为1、3和5的段落元素。由于索引以0开头,因此突出显示该段落在偶数位置。









 

Welcome to the javaTpoint.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.

输出量

执行上述代码后,输出为-

单击给定的按钮后,我们可以看到该函数返回索引位置为1、3和5的段落元素。索引的位置从0开始。