2012-05-30 67 views
0

如何將文本輸出到父母<div><span>?我究竟做錯了什麼? 如果有任何更好的解決方案比使用跨度和.parent(),請讓我知道。Jquery父母的跨度

HTML:

<div> 
<span></span> <!--the span where i want to output "troll" and "dwarf"--> 
<a href="#" class="heroes" alt="troll">Icon</a> 
<a href="#" class="heroes" alt="dwarf">Icon</a> 
</div> 

<div> 
<span></span <!--the span where i want to output "witch"--> 
><a href="#" class="heroes" alt="witch">Icon</a> 
</div> 

<div> 
<span></span> <!--etc...--> 
<a href="#" class="heroes" alt="barbarian">Icon</a> 
</div> 

<div> 
<span></span> 
<a href="#" class="heroes" alt="necromancer">Icon</a> 
</div> 

JS:

$('.heroes').hover(function() { 
    var hero = $(this).attr('alt'); 
    $(this).parent('span').text(hero); 
}, function() { 
    $(this).parent('span').text(""); 
}); 

感謝

回答

3
$(this).siblings('span').text(hero); 

跨度爲錨的兄弟,不是它的父。

縮進你的HTML,你可以看到它很容易:

<div> <!--The parent of the span and anchors!--> 
    <span></span> <!--Sibling of the anchors!--> 
    <a href="#" class="heroes" alt="troll">Icon</a> 
    <a href="#" class="heroes" alt="dwarf">Icon</a> 
</div> 

Live DEMO

注:alt不是錨有效的HTML屬性。

+0

「注意:alt不是錨的有效HTML屬性。」會造成什麼問題嗎?你有什麼建議,而不是alt? – John

+0

此外,關於「英雄」沒有在這個函數中定義「我想離開元素區域後文本消失,所以這就是爲什麼英雄不需要,只有空字符串:) – John

+0

@ user6613。有道理。 ... :) – gdoron

1

用途:

$(this).closest('div').find('span').text(hero); 

<span>是兄弟不是你的鏈接的父母,你可以找到它根據實際<div>父。

+0

'兄弟姐妹('span')'...不要往下走... :) – gdoron

+0

@gdoron:可選方式,因爲您已經發布了它。 – Sarfraz