javascript - Jquery 父级的跨度

标签 javascript jquery html

如何将文本输出给父级<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>

JS:

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

谢谢

最佳答案

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

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

缩进你的 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 不是 anchor 的有效 HTML 属性。

关于javascript - Jquery 父级的跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815007/

相关文章:

javascript - 我可以用 setTimeout 重置一个未绑定(bind)的函数吗?

jquery定位弹出

jquery - 将元素滚动到容器的顶部 onclick

jquery - jQuery .click 中的多个变量

html - 如何在 ul、li 标签中保留 img 元素的纵横比?

html - 跨度不适用于 Bootstrap 按钮

javascript - Highchart默认限制系列数量

javascript - 当用户停止点击时触发事件

javascript - 将 Mongoose 返回的数组转换为常规 JSON

javascript - 如果输入了正确的坐标,则启用复选框