我想要jquery在一個旋轉木馬的第一個裏面定位一個h2,然後我將添加一些css。只在第一個li中找到h2
作爲一個基本的例子,我有這個迄今爲止
$('li').first().css('background-color', 'red');
這是隻針對華里。然後,我如何繼續攻擊目標h2以將CSS應用於?它會使用.find屬性嗎?
我知道我可以在CSS中做到這一點,但想在jQuery中做到這一點,因爲它會在jQuery中添加其他功能。
我想要jquery在一個旋轉木馬的第一個裏面定位一個h2,然後我將添加一些css。只在第一個li中找到h2
作爲一個基本的例子,我有這個迄今爲止
$('li').first().css('background-color', 'red');
這是隻針對華里。然後,我如何繼續攻擊目標h2以將CSS應用於?它會使用.find屬性嗎?
我知道我可以在CSS中做到這一點,但想在jQuery中做到這一點,因爲它會在jQuery中添加其他功能。
「會使用.find屬性嗎?」
嗯,是的,find()
method(不屬性)是如何做這件事:
// all h2 elements within the first li:
$('li').first().find('h2').css('background-color', 'red');
// or just the first h2 within the first li:
$('li').first().find('h2').first().css('background-color', 'red');
,或者你可以嘗試,如果h2
是一個在DOM來li
下級:
// all h2 elements within the first li:
$('li').first().children('h2').css('background-color', 'red');
因爲find()多級使其變慢。
()方法從.find()在不同。孩子的。孩子()只行進的單一電平向下DOM樹而.find()可以向下遍歷多個級別來選擇後代元素(孫子,等等)。 documented here
試試這個:
$('li:first h2').css('background-color', 'red');
打我吧,+1 –
輝煌非常感謝你! – Megan