国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 崇信县| 衡阳县| 浮梁县| 新巴尔虎右旗| 郁南县| 睢宁县| 宝兴县| 孝感市| 瑞昌市| 莱州市| 贞丰县| 泸水县| 定边县| 望奎县| 体育| 浠水县| 凌云县| 正安县| 抚宁县| 仪陇县| 出国| 奉化市| 崇仁县| 北碚区| 子洲县| 克拉玛依市| 绥棱县| 河曲县| 邢台县| 习水县| 奉贤区| 毕节市| 晴隆县| 涿州市| 冷水江市| 江西省| 凤城市| 巴东县| 乡城县| 河南省| 南部县|