简体   繁体   English

JavaScript MouseOver图片

[英]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. 使用前请先查看是否已包含jQuery库。
  2. You have to put your code inside $(document).ready(function(){ //here your code goes }); 您必须将代码放入$(document).ready(function(){ //代码在这里})内;

Try this way, 试试这个

HTML : HTML:

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

jQuery : 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 jsFiddle

Why your code didn't work????? 为什么您的代码不起作用????

Before manipulating any DOM element, the page must be loaded first. 在操作任何DOM元素之前,必须先加载页面。 So one question arises that, 因此出现一个问题,

How would I know if the page has already been loaded!!! 我怎么知道页面是否已经加载!

Here comes $(document).ready(); 这是$(document).ready(); as a helping hand from jQuery . 作为jQuery的帮手。 It let javaScript execute the code that it contains when the DOM elements are ready for use. 当DOM元素准备好使用时,它使javaScript执行它包含的代码。 So as a developer you don't need to worry if DOM has been loaded or not. 因此,作为开发人员,您不必担心DOM是否已加载。

And that's the reason that you were going to manipulate the DOM element #myImg before it has been availabe for use. 这就是您要在DOM元素#myImg可用之前对其进行操作的原因。 And your javaScript/jQuery code couldn't find that you are asking for. 而且您的javaScript / jQuery代码找不到您要的。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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