我写了这个代码,这是一个评级系统。 我想要发生的事情是,当你将鼠标悬停在一颗恒星上时,星星应该触发它。jQuery toArray函数和如何使用其元素
每当我将鼠标悬停在一颗恒星上时,就会发生图片变化,但是它之前的恒星没有变化。
$('.star').hover(function(){
$(this).children().attr('src','StarsRating/star_yellow.png');
var count=$(this).attr('data-count');
var starArray =$('.star').toArray();
for(i=0; i<count; i++){
//The problem is here. the attributes of the stars should change to star_yellow.png..but they dont
console.log(starArray [i]); $(starArray [i])。attr('src','StarsRating/star_yellow.png'); }
},function(){
$(this).children().attr('src','StarsRating/star_grey.png');
});
HTML:
<div id="ratingStars">
<div class="star" data-count="1">
<img src="StarsRating/star_yellow.png"/>
</div>
<div class="star" data-count="2">
<img src="StarsRating/star_grey.png"/>
</div>
<div class="star" data-count="3">
<img src="StarsRating/star_grey.png"/>
</div>
<div class="star" data-count="4">
<img src="StarsRating/star_grey.png"/>
</div>
<div class="star" data-count="5">
<img src="StarsRating/star_grey.png"/>
</div>
UPDATE这就是我得到的,当我把控制台内部的循环:
<div class="star" data-count="1" src="StarsRating/star_yellow.png">…</div>
newEmptyPHPWebPage.php:41
<div class="star" data-count="2" src="StarsRating/star_yellow.png">…</div>
newEmptyPHPWebPage.php:41
<div class="star" data-count="3" src="StarsRating/star_yellow.png">…</div>
但为什么我可以看到,它开启TEH控制台,但不在文档上?
我真的,不认为它很重要 – 2012-08-06 18:20:54
你的代码有一个逻辑错误,因为你选择了一个明星的孩子,而不是星星的容器。我已经更新了我的回答 – Sindre 2012-08-06 18:27:03
是的,它的确如此。 '.children()'发现层次低于DOM中目标元素的元素,而不仅仅是那些出现在源代码中的元素。你盘旋的明星元素没有孩子。它有兄弟姐妹,所以'$(this).siblings('。star')'会起作用,就像$(this).parent()。children('。star')' – jackwanders 2012-08-06 18:27:46