2013-05-19 35 views
-2

我不明白爲什麼代碼的最後一部分會影響第二個div而不是第一個像第一個那樣。另外,那裏的所有其他內容都消失了,這不是理想的行爲。我正在閱讀的書沒有解釋爲什麼第二個div受到影響,而不是第一個。爲什麼這發生在第二個而不是第一個?我認爲div:last-child會改變第一個div,因爲它被認爲是直系父母。與子元素的jQuery問題

jQuery的

$(document).ready(function(){ 
    $('div:first-child').text('This is the first child'); 
    $('div:last-child').text('I\'ve changed this!'); 
}); 

HTML

<div id=」myfirstdiv」> 
    <strong class=」changemytext」>some name</strong> 
    <p class=」changemytext」>Some text<p> 
    <strong>another name</strong> 
    <p>More text<p> 
</div> 

<div id=」myseconddiv」> 
    <strong class=」changemytext」>some name</strong> 
    <p class=」changemytext」>Some text<p> 
    <strong>another name</strong> 
    <p>More text<p> 
</div> 
</body> 

+0

什麼你想在這裏做什麼? –

+0

我深信,只有那些元素會受到影響,正如我在上面所說的那樣,但是,第一個父母的第一個元素髮生了變化,第二個元素的變化也是如此,但其餘的內容也都消失了。我認爲第一個div的第一個和最後一個元素只會受到影響。 –

+0

感謝科迪簡化我的代碼。 –

回答

1

第一胎使你打第一個選項可用,最後孩子使你打到最後一個(第二次在這種情況下,如果你沒有添加僞選擇器,他們會同時擊中他們兩個。

+0

好的。謝謝,本。 –

1

我會簡化LY翻譯您的選擇:

//$(The divs that the first child of their parents).text('This is the first child'); 
$('div:first-child').text('This is the first child'); 

//$(The divs that the last child of their parents).text('I\'ve changed this!'); 
$('div:last-child').text('I\'ve changed this!'); 
1

:first-child Selector基本選擇是他們的父母的第一個孩子的所有元素。

:last-child Selector選擇作爲其父項的最後一個子元素的所有元素。

這裏,父是body和第一個div是第一胎這裏的第二個div是最後孩子這裏您得到預期的結果。

什麼你正在努力實現需要做這樣的:

$(document).ready(function() { 
    $('div :first-child').text('This is the first child'); 
    $('div :last-child').text('I\'ve changed this!'); 
}); 
+0

就是這樣啊!謝謝。我曾想過,第一個div是父母,所以我的困惑!非常感謝!。 –