JQuery Tips(3) 關于$()包裝集內元素的改變
2024-05-06 14:12:21
供稿:網友
這兩個方法是比較容易搞混的.
filter方法表示的是對當前內部的元素進行篩選,這個接受兩種參數,一個返回bool的function,或者是JQuery的選擇表達式,包裝集內的元素只會小于等于當前包裝集內的元素,并且含有的元素屬于原來包裝集內元素的子集:
代碼如下:
<div id="one">the one</div>
<div id="two"><p>the two</p></div>
<div id="three"><p>the three</p></div>
<script type="text/javascript">
alert($("div").filter(":not(:first):not(:last)").html()); //out put<p>the two</p>
alert($("div").filter(function() { return this.id == "two"; }).html());//output <p>the two</p> as well
</script>
而find方法卻是在當前元素內(子元素)部進行查找,并返回新的包裝集,這意味著包裝集可能會增加:
代碼如下:
<div id="one">the one</div>
<div id="two"><p>the two</p><p></p><p></p></div>
<div id="three"><p>the three</p></div>
<script type="text/javascript">
alert($("div").find("p").text()); //alert "the twothe three"
alert($("div").find("p").length); //alert 4 instead of original 3
</script>
從上面可以看出新包裝集內的元素增加了
parents()方法 VS closest()方法
這兩個方法都是由當前元素向上查找所匹配的元素,不同之處如下:
代碼如下:
<div id="wrapper">
<div id="two">
<p id="p1">
the two</p>
</div>
</div>
<script type="text/javascript">
alert($("#p1").parents("div").length); //alert 2 include <div id="two"> and <div id="wrapper">
alert($("#p1").closest("div").length); //alert 1 and only include <div id="two">
alert($("#p1").parents("p").length); //alert 0 because it does not include current element
alert($("#p1").closest("p").length); //alert 1 because it contain itself <p id="p1">
</script>
對于parents方法來說,會將當前元素向上的所有匹配元素加入新的包裝集并返回,而closest方法只會包含離當前元素最近的元素,所以使用closest方法后當前包裝集內的元素只能為1個或者0個
而parents方法并不包括當前包裝集內的元素,而closest方法會包含當前包裝集內的元素
直系子元素 VS 所有子元素
使用children可以返回直系子元素,而用find加通配符的方法可以返回除了文本節點之外的所有子元素:
代碼如下:
<div id="wrapper">
text node here
<div id="two">
<p id="p1">
the two</p>
</div>
</div>
<script type="text/javascript">
alert($("#wrapper").children().length);//alert 1 because only direct children included
alert($("#wrapper").find("*").length); //alert 2 because all desendants included