[jquery]find与filter的应用
星期三, 四月 14th, 2010, 18:30 | YSjia 点击3254次.find()
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector.
查找子元素,反回一个新的jQuery Object,与.children()选择器相同,而两个选择器唯一不同的是.children()只能返回一个级别的元素。
e.g.
<div id="t1" class="demo1"><div class="demo2"><div class="demo3"></div></div> </div>
$("#t1").children(); //return [div.demo2]
$("#t1").find("div"); //return [div.demo2, div.demo3]
$("#t1").children(".demo3"); //return []
.fliter()
Description: Reduce the set of matched elements to those that match the selector or pass the function’s test.
对选择元素的子集,进一步筛选。正如其名一样fliter,是一个过虑嘴。
这里有个问题,还是Ajax加载HTML的问题
一个远程的HTML

用Ajax加载
$.get({ url: "test.html",function(data){
var $d=$(data);
var $filter = $(data).filter(".ajaxpage");
var $find = $(data).find(".ajaxpage");
}});
其中$filter可以正确取到div.ajaxpage
而$find则返回是[]
在前一篇文章中[jQuery]当$遇上HTML说过当jQuery异步加一个HTMl文档后,会将其转化为NodeList类型。
这样就是对数组中的成员进行相应的筛选。
再来看一下jQuery的源码是如何处理的,.filter()与.find()都去判断需要筛选的元素的类型(nodeType)与选择器(Selector),然后再用grep函数与Sizzle等函数组新的数组。
filter用的是grep函数
grep函数的作用
源函数注释
// Go through the array, only saving the items that pass the validator function
判断data内各个元素的nodeType的类型,将element类型封装到一起,组成一个新的数组。
然后判断filter的类型是ID、Class或其他,进而在数据内排查找到相应的成员并返回。
find函数开始时用了一个pushStack一个堆栈
源函数注释
// Take an array of elements and push it onto the stack (returning the new matched element set)
进而由Sizzle函数对每个数组成员进行匹配与筛选,如果是Class就由find.CLASS函数进行进一步筛选其中有句
context.getElementsByClassName(match[1]);
这句就是find的核心,就是说find函数是对子节点进行筛选
所以切记find与filter的不同在于,一个是对于子节点的筛选,另一个是对搜索结果的进一步过滤,由其在异步加载HTML文档时的筛选要应用正确的函数才能更好的发挥jQuery的强大。
顺便回顾一下nodeType
nodeType
nodeType 属性可返回节点的类型。
最重要的节点类型是:
| 元素类型 | 节点类型 |
| 元素element | 1 |
| 属性attr | 2 |
| 文本text | 3 |
| 注释comments | 8 |
| 文档document | 9 |
如果你喜欢请+1
Tags: javascript, jQuery
你的文章页始终看起来蒙蒙的
[回复]
指的是字体的颜色?
[回复]
难道。。技术的沙发?
[回复]
呵呵,我的沙发不用抢~
[回复]