鼠标悬停效果在每个项目上运行

时间:2012-05-16 05:59:42

标签: javascript jquery hover

我在一个页面上发生了5次UL。因此,当我鼠标悬停在一个图像上时,每个UL实例都会产生相同的效果(即它会改变所有5个出现的HTML)。

我想在单独的UL上执行脚本,以便效果在相应的UL上运行,鼠标悬停而不是全部。

实时代码示例:http://jsfiddle.net/5FPSc/

提前致谢。任何帮助/指针都会有很大的帮助。 / GSA

HTML:

<ul class="answerOptions">
    <li data-score="0" data-answer="A" class="answer-1">
      <figure><img src="assets/images/styles/quiz/ques2_A.jpg" alt="" title="" />
        <figcaption>Dinner and a movie</figcaption>
      </figure>
    </li>
    <li data-score="1" data-answer="B" class="answer-2">
      <figure><img src="assets/images/styles/quiz/ques2_B.jpg" alt="" title="" />
        <figcaption>2 words: Laser Tag</figcaption>
      </figure>
    </li>
    <li data-score="0" data-answer="C" class="answer-3">
      <figure><img src="assets/images/styles/quiz/ques2_C.jpg" alt="" title="" />
        <figcaption>Stroll through the park and a picnic</figcaption>
      </figure>
    </li>
    <li data-score="0" data-answer="D" class="answer-4">
      <figure><img src="assets/images/styles/quiz/ques2_D.jpg" alt="" title="" />
        <figcaption>Skydiving</figcaption>
      </figure>
    </li>
    <li data-score="4" data-answer="E" class="answer-5">
      <figure><img src="assets/images/styles/quiz/ques2_E.jpg" alt="" title="" />
        <figcaption>Art gallery and wine tasting</figcaption>
      </figure>
     </li>
</ul>
    <div class="answerItem-1"></div>

脚本:

$('.answerOptions figure').hover(function(){
    $(".answerItem-1").html($(this).find("figcaption").html());
},function(){
if($('figure').hasClass('selected') != true){
    $(".answerItem-1").html("");
}
else {
      $(".answerItem-1").html($("figure.selected").find("figcaption").html());
}
}); 
$('.answerOptions figure').click(function(){    
    $('figure').removeClass('selected');
    $(this).addClass("selected");   
    $(".answerItem-1").html($(this).find("figcaption").html());
});

3 个答案:

答案 0 :(得分:0)

不要使用类,请使用Id。类悬停效果在所有项目上运行,id在页面上只能是一个。

答案 1 :(得分:0)

他们全部“弹出”的原因是因为这一行:$(".answerItem-1")你选择的是每一个.answerItem-1并且你有一堆这些。 您需要设置唯一标识符。我会做这样的事情:

<figure rel="q1">
...
<div id="q1" class="answerItem-1"></div>

//jquery code
var q = $(this).attr('rel');  
$('#'+q).html($(this).find("figcaption").html());

http://jsfiddle.net/5FPSc/4/

答案 2 :(得分:0)

我认为你应该使用客观概念,使LI标签拥有自己的事件处理程序。 只需查看以下脚本,即可参考您的代码。

$('ul.answerOptions').delegate('li.answer-1', 'hover', function(event) {

    if (event.type == 'mouseenter') {
        console.log('inbound');
        var $target = $(this).parents('div.question').find('div.answerItem-1');
        var showText = '';
        showText = $(this).find('figcaption').html();
        $target.html(showText);
    } else if (event.type == 'mouseleave') {
        var $target = $(this).parents('div.question').find('div.answerItem-1');
        $target.html('');
    }
});​