ajax find,.find()

本文详细解析了jQuery的find()方法,介绍了其在DOM树中搜索子元素并进行筛选的过程。通过实例展示了如何使用选择器过滤后代元素,并区分了它与children()方法的区别。此外,讲解了如何结合selector context和jQuery对象进行更复杂的筛选操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

The first signature for the .find()method accepts a selector expression of the same type that we can pass to the $() function. The elements will be filtered by testing whether they match this selector; all parts of the selector must lie inside of an element on which .find() is called. The expressions allowed include selectors like > p which will find all the paragraphs that are children of the elements in the jQuery object.

Consider a page with a basic nested list on it:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

  • I
  • II
    • A
    • B
      • 1
      • 2
      • 3
    • C
  • III

If we begin at item II, we can find list items within it:

1

$( "li.item-ii" ).find( "li" ).css( "background-color", "red" );

The result of this call is a red background on items A, B, 1, 2, 3, and C. Even though item II matches the selector expression, it is not included in the results; only descendants are considered candidates for the match.

Unlike most of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

Selector context is implemented with the .find() method; therefore, $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).

As of jQuery 1.6, we can also filter the selection with a given jQuery collection or element. With the same nested list as above, if we start with:

1

var allListElements = $( "li" );

And then pass this jQuery object to find:

1

$( "li.item-ii" ).find( allListElements );

This will return a jQuery collection which contains only the list elements that are descendants of item II.

Similarly, an element may also be passed to find:

1

2

var item1 = $( "li.item-1" )[ 0 ];

$( "li.item-ii" ).find( item1 ).css( "background-color", "red" );

The result of this call would be a red background on item 1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值