簡體   English   中英

jQuery父母的跨度

[英]Jquery parent's span

如何將文本輸出到父<div><span> 我究竟做錯了什么? 如果有比使用.parent().parent()更好的解決方案,請告訴我。

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("");
});

謝謝

$(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>

現場演示

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

采用:

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

<span>不是您的鏈接的父級,您可以根據實際的<div>父級找到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM