简体   繁体   中英

passing parameters into function

I am very new to javascript and I hope to get some help simplifying the code.

I have two div box that contains 3 images each. Each div box displays an image by default (no. 1 and 4) and the mouse hover toggle a change in image (independently). See http://jsfiddle.net/hdaq9se5/6/ .

The following code works just right but I am hoping to get some help simplifying the code, eg modify the animation function such that it takes the class of the div box as input.

$(document).ready(function () {
    $("#image_two, #image_three, #image_five, #image_six").hide();
    $(".image_rollover").hover(function () {
       animation()
    });

     $(".image_rollover2").hover(function () {
       animation2()
    });
});

function animation() {
    var $curr=$(".image_rollover img:visible");
    var $next=$curr.next();    

    if($next.size()==0) $next=$(".image_rollover img:first");

    $next.show();
    $curr.hide();
}

function animation2() {
    var $curr=$(".image_rollover2 img:visible");
    var $next=$curr.next();    

    if($next.size()==0) $next=$(".image_rollover2 img:first");

    $next.show();
    $curr.hide();
}

Like this?

Using jquery, this is in most places (almost everywhere) the current Element. Like the Element that dispatched an event, ...

knowing this you don't need to pass any classes into animation , jquery already provides you with all you need.

 $(document).ready(function() { $(".image_box img").not(":first-child").hide(); $(".image_box").hover(animation); }); function animation() { var $curr = $("img:visible", this); var $next = $curr.next(); if ($next.length === 0) { $next = $("img:first", this); } $next.show(); $curr.hide(); }
 .image_box { border: 1px solid #000000; width: 130px; height: 80px; overflow: hidden; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="image_rollover image_box"> <img id="image_one" src="http://placehold.it/130x80&text=1"> <img id="image_two" src="http://placehold.it/130x80&text=2"> <img id="image_three" src="http://placehold.it/130x80&text=3"> </div> <div class="image_rollover2 image_box"> <img id="image_four" src="http://placehold.it/130x80&text=4"> <img id="image_five" src="http://placehold.it/130x80&text=5"> <img id="image_six" src="http://placehold.it/130x80&text=6"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM