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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742392853a4435357.html
评论列表(0条)