如何使用JQuery提供多个div,一次在一个div上应用切换幻灯片效果?

时间:2012-02-24 12:59:08

标签: jquery

JS:

$(function () {      
    function runEffect() {           
        var options = {};            
        $(".effect").toggle('slide', options, 500/*time*/);
    };
    $(".button").click(function () {
        runEffect();
        return false;
    });
});

HTML:

<div class="riddle1">
<div class="riddle-answer"> 
        <a href="#" class="button" style="float:left;">
         <img src="" width="45" height="112" title="" alt="Answer" /></a>
        <div class="effect">    
        <p>Test riddle Test riddle Test riddle Test riddle Test riddle Test riddle</p>
       </div>
</div>

<div class="riddle-top"></div>

<div class="riddle-mid">
 <p>If three cats catch three mice in three minutes, how many cats would be needed to catch 100 mice in 100 minutes? </p>
</div>

<div class="riddle-bot"></div>

    riddle2还有另一个div与上面相同,但是现在当点击图像链接时,它会对框或DIVs-riddle1和riddle2应用切换效果。如果使用按钮和效果作为id而不是类,可以将切换效果应用于一个DIV。那么如何将切换效果同时应用于两者之一。

1 个答案:

答案 0 :(得分:3)

这是因为您在选择$(".effect")时不使用上下文,因此它会选择文档中具有类effect的所有元素。

这是一种能够在runEffect()方法中选择上下文的方法:

    点击处理程序e.currentTarget中的
  • 是冒泡阶段的当前元素

  • 将其作为参数传递给runEffect()方法

  • 在runEffect()方法中,用它来查询相应的“.effect”元素

以下是代码:

$(function () {      
    function runEffect(context) {         
        var options = {};            
        $(context).siblings('.effect').toggle('slide', options, 500/*time*/);
    };
    $(".button").click(function (e) {
        runEffect(e.currentTarget);
        return false;
    });
});​

<强> DEMO