2012-11-20 24 views
2

我有一個父元素,每個子元素需要不同的更改。有一個簡單的解決方案,但我想知道鏈接是否可能並且會更有效率。jQuery:鏈接多個子元素

一個很簡單的例子:

<div id="parent"> 
    <div class="one">One</div> 
    <div class="two">Two</div> 
    <div class="three">Three</div> 
</div> 

---------------------- 

$('#parent .one').text('Some'); 
$('#parent .two').text('Thing'); 
$('#parent .three').text('Else'); 

有沒有辦法做類似這樣的東西嗎?

$('#parent') 
    .children('.one').text('Some') 
    .children('.two').text('Thing') 
    .children('.three').text('Else'); 

其中每個孩子將鏈條重置回父母。另外,除了使代碼更容易閱讀之外,這會有效嗎?記住,這是澄清問題的一個非常簡單的例子。我不是指這個確切的代碼。我非常感謝幫助。謝謝。

回答

9

end()將鏈條返回到它是最後過濾前:

$('#parent') 
    .children('.one').text('Some').end() 
    .children('.two').text('Thing').end() 
    .children('.three').text('Else'); 
+0

完美。謝謝! – user1449855

2
$('#parent') 
    .find('.one').text('Some') 
    .siblings('.two').text('Thing') 
    .siblings('.three').text('Else'); 
+0

這將在OP示例中起作用,但假定項目將始終爲「有序」,可能並非總是爲真 –

+0

爲真...但在這種情況下,您始終可以用'兄弟'替換'下一個'。 – Derek

+0

這樣做,你會得到我的upvote :) –