Jquery 父级的跨度

Joh*_*ohn 0 html javascript jquery

如何将文本输出到父<div><span>?我究竟做错了什么?如果有比使用 span 和 更好的解决方案.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>
Run Code Online (Sandbox Code Playgroud)

JS:

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

谢谢

gdo*_*ica 5

$(this).siblings('span').text(hero);
Run Code Online (Sandbox Code Playgroud)

跨度是锚点的同级,而不是其父级。

缩进你的 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>
Run Code Online (Sandbox Code Playgroud)

现场演示

注意: alt不是锚点的有效 HTML 属性。