admin管理员组文章数量:1335607
How can I output the text to the parent <div>
's <span>
? What am i doing wrong?
If there are any better solutions than working with spans and .parent()
, please let me know.
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("");
});
Thanks
How can I output the text to the parent <div>
's <span>
? What am i doing wrong?
If there are any better solutions than working with spans and .parent()
, please let me know.
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("");
});
Thanks
Share Improve this question edited May 30, 2012 at 11:12 gdoron 150k59 gold badges302 silver badges371 bronze badges asked May 30, 2012 at 11:05 JohnJohn 1,6299 gold badges24 silver badges34 bronze badges2 Answers
Reset to default 5$(this).siblings('span').text(hero);
The span is a sibling of the anchor, not it's parent.
Indent your HTML, and you see it very easily:
<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
Note: alt
isn't a valid HTML attribute for an anchor.
Use:
$(this).closest('div').find('span').text(hero);
<span>
is sibling not parent of your links, you can find it based on actual <div>
parent.
本文标签: javascriptJquery parent39s spanStack Overflow
版权声明:本文标题:javascript - Jquery parent's span - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742392852a2466333.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论