天天看點

jquery中後代元素和子元素的差別

對于剛學jquery的朋友來說,有時候會對jquery的層選擇器$("ancestor descendant")和$("parent>child")産生一點了解上的問題。其實很簡單,看完下面的例子你就會完完全全明白了。

<div>This is <strong>very</strong> important.</div>

<div>This is <em>really <strong>very</strong></em> important.</div>

以上是html。運作後在浏覽器裡是看到

This is  very important. This is  really very important.  

這樣的樣式,為了容易看到效果,我們不妨就嘗試用添加css顔色來試一下

如果運作$("div strong").css("color","red");就是把div的後代元素strong變為紅色。運作後是

This is  very important. This is  really very important.     如果運作$("div>strong").css("color","blue");就是把div的子元素strong變為藍色。運作後是   This is  very important. This is  really very important.

說明:後代元素是之後的所有元素;子元素是之後的元素。

比如: 張三和父親、爺爺之間的關系可以如下表述:

爺爺的後代元素是:張三和父親; 爺爺的子元素是:父親。