質問

So I am doing something very basic that can be done with CSS but I want to do it with jQuery to get familiar with the library.

I am trying to create a rollover image gallery. Where when you put the mouse over the image it will be swapped with a slightly edited version of it.

Here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<style>

</style>
</head>
<body>
<div id="gallery">
    <a href="#"><img src="images/one_s.jpg" /></a>
    <a href="#"><img src="images/two_s.jpg" /></a>
    <a href="#"><img src="images/three_s.jpg" /></a>
    <a href="#"><img src="images/four_s.jpg" /></a>
    <a href="#"><img src="images/five_s.jpg" /></a>
    <a href="#"><img src="images/six_s.jpg" /></a>
</div>
<script>
$(document).ready(function(){

    var alternate = ['images/one_s_edited.jpg',
                    'images/two_s_edited.jpg',
                    'images/three_s_edited.jpg',
                    'images/four_s_edited.jpg',
                    'images/five_s_edited.jpg',
                    'images/six_s_edited.jpg'];

    var $selection = $("#gallery img");

    for(var i = 0; i < alternate.length; i++)
    {

        var imgObject = new Image();

        var downloadedImg = imgObject.src = alternate[i];

        console.log(downloadedImg);

        var originalSrc = $selection.eq(i).attr("src");

        console.log(originalSrc + "\n");

        $selection.eq(i).hover(
            function(){
                $(this).attr("src", downloadedImg);
            },
            function(){
                $(this).attr("src", originalSrc);
            }
        );//End hover

    }//End loop
});//End ready
</script>
</body>
</html>

Here is a link to the final result: link

As you can see it rolls over but not as planned. It ends up with the last rollover-image and doesn't change back to the original nor does it show the appropriate rollover image that corresponds with it.

Any simple suggestions without using regular expressions?

役に立ちましたか?

解決

The problem is the wrong usage of a closure variable in a loop.

But the solution can be simplified to

$(document).ready(function () {
    var $selection = $("#gallery img");
    $selection.hover(function () {
        this.src = this.src.replace('.jpg', '_edited.jpg')
    }, function () {
        this.src = this.src.replace('_edited.jpg', '.jpg')
    })
}); //End ready
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top