2014-01-05 43 views
0

如何使用jQuery捕獲兄弟元素,即父元素中的子元素?捕獲jQuery中父元素中的子元素

HTML

<div class="fruit"> 
    <div class="apple"></div> 
    <a class="mango"></a> 
</div> 

jQuery的

$(".apple").bind("mouseover", function() { 
    $(this).parent.child(".mango").text("banana"); 
}); 
+1

母體是一種方法,而不是一個屬性:'.parent()'HTTP:// API .jquery.com/parent/ –

+1

另外,還有一個'children()'方法,但沒有'child()'方法。 –

+0

@FrédéricHamidi哎呀,這也是真的 –

回答

2

DEMO:http://jsfiddle.net/5Y9mG/5/
試試這個:

$(".apple").bind("mouseover", function() { 
       $(this).siblings(".mango").text("banana"); 
    }); 
+0

@Faizan:它應該工作:) –

+0

你是對的! :) – Faizan

2

使用jQuery的next()siblings()功能:

$(".apple").bind("mouseover", function() { 
    $(this).next().text("banana"); 
}); 
+0

「.next()」不是最終的解決方案,它在這種情況下工作,但不是如果有兩個以上的元素和我想要的元素很遠 – Faizan

+0

它適用於OP今後,將這些要求添加到問題中。 –

1

給你控制一個孩子,需要針對兄弟,第一參考父,然後開始尋找裏面。

在這裏,我們首先通過使用$(this).parent()目標父,然後我們看該父內部使用find(".mango")

$(".apple").bind("mouseover", function() { 
    $(this).parent().find(".mango").text('banana'); 
});