简体   繁体   中英

JavaScript MouseOver Image

I am trying to change the picture by using mouseover however it doesn't seem to be working? can anyone help? here is my code

<img id="myImg" src="Nov1.jpg" alt="November" style="width:452px;height:127px">

  <script>
  $('#myImg').hover(function() {
    $(this).attr('src', '/folder/nov2014.jpg');
   }, function() {
   $(this).attr('src', '/folder/Nov1.jpg');
  });


  </script>

There might be two reasons that can create such problem.

  1. See if you've included the jQuery library before using it.
  2. You have to put your code inside $(document).ready(function(){ //here your code goes });

Try this way,

HTML :

<img id="myImg" src="http://www.allgraphics123.com/ag/01/14142/14142.gif" />

jQuery :

$(document).ready(function(){
    $('#myImg').hover(function() {
        $(this).attr('src', 'http://thumb7.shutterstock.com/display_pic_with_logo/265489/120305665/stock-vector-cartoon-parrot-vector-clip-art-illustration-with-simple-gradients-all-in-a-single-layer-120305665.jpg');
        }, function() {
        $(this).attr('src', 'http://www.allgraphics123.com/ag/01/14142/14142.gif');
    });
});

jsFiddle

Why your code didn't work?????

Before manipulating any DOM element, the page must be loaded first. So one question arises that,

How would I know if the page has already been loaded!!!

Here comes $(document).ready(); as a helping hand from jQuery . It let javaScript execute the code that it contains when the DOM elements are ready for use. So as a developer you don't need to worry if DOM has been loaded or not.

And that's the reason that you were going to manipulate the DOM element #myImg before it has been availabe for use. And your javaScript/jQuery code couldn't find that you are asking for.

I just rephrased this documentation : Here

Try:

  <img id="myImg" src="Nov1.jpg" alt="November" style="width:452px;height:127px">

  <script>

    $("#myImg")
            .mouseover(function() {
                $(this).attr("src", "/folder/nov2014.jpg");
            })
            .mouseout(function() {
                $(this).attr("src", "/folder/Nov1.jpg");
            });   
  </script>

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