jQuery 獲取兄弟元素的幾種不錯方法
更新時間:2014年05月23日 10:28:46 作者:
這篇文章主要介紹了jQuery 獲取兄弟元素的幾種不錯方法,需要的朋友可以參考下
獲取指定元素的兄弟元素時,可以使用adjacent sibling combinator (+),其中+的兩側(cè)內(nèi)容都是selector expression.
如果要獲取下例中所有的 h1的直接兄弟元素h2
<div>
<h1>Main title</h1>
<h2>Section title</h2>
<p>Some content...</p>
<h2>Section title</h2>
<p>More content...</p>
</div>
可以直接使用
$('h1 + h2')
// Select ALL h2 elements that are adjacent siblings of H1 elements.
如果要過濾h1的兄弟元素,當(dāng)然也可以使用
$('h1').siblings('h2,h3,p');
// Select all H2, H3, and P elements that are siblings of H1 elements.
如果要獲取當(dāng)前元素之后的所有兄弟元素,可以使用nextAll()
例如,針對下面的html代碼
<ul>
<li>First item</li>
<li class="selected">Second Item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>
如果要獲取第二個條目之后的所有l(wèi)i元素,可以使用如下代碼
$('li.selected').nextAll('li');
上例也可以使用general sibling combinator (~)來實現(xiàn)
$('li.selected ~ li');
獲取直接兄弟元素也可以不使用selector,直接使用next().
var topHeaders = $('h1');
topHeaders.next('h2').css('margin', '0);
如果要獲取下例中所有的 h1的直接兄弟元素h2
復(fù)制代碼 代碼如下:
<div>
<h1>Main title</h1>
<h2>Section title</h2>
<p>Some content...</p>
<h2>Section title</h2>
<p>More content...</p>
</div>
可以直接使用
復(fù)制代碼 代碼如下:
$('h1 + h2')
// Select ALL h2 elements that are adjacent siblings of H1 elements.
如果要過濾h1的兄弟元素,當(dāng)然也可以使用
復(fù)制代碼 代碼如下:
$('h1').siblings('h2,h3,p');
// Select all H2, H3, and P elements that are siblings of H1 elements.
如果要獲取當(dāng)前元素之后的所有兄弟元素,可以使用nextAll()
例如,針對下面的html代碼
復(fù)制代碼 代碼如下:
<ul>
<li>First item</li>
<li class="selected">Second Item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>
如果要獲取第二個條目之后的所有l(wèi)i元素,可以使用如下代碼
復(fù)制代碼 代碼如下:
$('li.selected').nextAll('li');
上例也可以使用general sibling combinator (~)來實現(xiàn)
復(fù)制代碼 代碼如下:
$('li.selected ~ li');
獲取直接兄弟元素也可以不使用selector,直接使用next().
復(fù)制代碼 代碼如下:
var topHeaders = $('h1');
topHeaders.next('h2').css('margin', '0);
相關(guān)文章
jQuery簡單實現(xiàn)點擊文本框復(fù)制內(nèi)容到剪貼板上的方法
這篇文章主要介紹了jQuery簡單實現(xiàn)點擊文本框復(fù)制內(nèi)容到剪貼板上的方法,涉及jQuery針對瀏覽器的判定與剪貼板的讀寫操作技巧,需要的朋友可以參考下2016-08-08
JQuery中兩個ul標(biāo)簽的li互相移動實現(xiàn)方法
這篇文章主要介紹了JQuery中兩個ul標(biāo)簽的li互相移動實現(xiàn)方法,可實現(xiàn)ul標(biāo)簽中l(wèi)i標(biāo)簽內(nèi)容相互替換的技巧,涉及jQuery操作頁面元素的相關(guān)技巧,需要的朋友可以參考下2015-05-05
jquery動畫4.升級版遮罩效果的圖片走廊--帶自動運(yùn)行效果
我將上一章中了插件做了個小小的升級,實現(xiàn)了自動運(yùn)行效果,完整代碼大家見demo2012-08-08

