如何将文本输出给父级<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>
注意: alt
不是 anchor 的有效 HTML 属性。
关于javascript - Jquery 父级的跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10815007/