jQuery中find()方法和filter()方法的區別
阿新 • • 發佈:2019-02-13
jQuery官方的API這樣說明filter和find函式:
filter(selector): Description: Reduce the set of matched elements to those that match the selector or pass the function’s test. find(selector): Description: Get the descendants of each element in the current set of matched elements, filtered by a selector.
find()會在當前指定元素中查詢符合條件的子元素,是對它的子集操作,而filter()則是在當前指定的元素集合中查詢符合條件的元素,是對自身集合元素進行篩選。
看下邊的例子就會一目瞭然:
HTML程式碼:<div class="benben"> <p>Hello,World!</p> <p>Hello,World Again!</p> <p class="test">Test1</p> </div> <div class="test"> <p>Test2</p> </div>
jQuery程式碼:
<script type="text/javascript">
//using find()
var $find=$("div").find(".test");
alert($find.html());//display "Test1"
//using test()
var $filter=$("div").filter(".test");
alert($filter.html());//display "Test2"
</script>
很多時候經常用到find()或者filter(),下邊的程式碼中就用到了find()方法在指定元素中查詢符合條件的子元素。
<script type="text/javascript"> $(document).ready(function() { //mouse hover $("ul.test>li").hover(function() { $(this).find("a:first").css({ "background":"white", "position":"relative" }); }, //mouse out function(){ $(this).find("a:first").css({ "background":"", "position":"" }); }); }); </script>
參考:http://www.benben.cc/blog/?p=352