开发者

I'm trying to change an Image's src attribute when the mouse hovers above it. Is there a reason why this JQuery code shouldn't work?

$('.icon1').mouseover(function(){
   $(this).find('img').attr('src', 'recursos/botban/maq1开发者_StackOverflow.png');
});

Should work right? It's just an arbitrary test to see what was wrong, but it's still broken.

I've also tried with $('.icon1').hover(function(){..., and it also does not work.

What I really want is more like...

$('.icon1').mouseover(function(){
        var alt = $(this).find('img').attr('src')+'.png';
        $(this).find('img').attr('src', $(this).attr('id')+''.png);
}).mouseout(function(){
        $(this).find('img').attr('src', alt);
});

The HTML for each image is as follows...

<a class='icon1'><img src='recursos/botban/veh1.png'></a>


A few things, I'd use mouseenter instead of mouseover (since mouseout will fire when entering a child), and also make sure it's running inside a document.ready handler, like this:

$(function() {
  $('.icon1').each(function(){
    $.data(this, 'src', $(this).find('img').attr('src'));
  }).hover(function(){
    $(this).find('img').attr('src', this.id + '.png'); //may need adjustment
  }).mouseout(function(){
    $(this).find('img').attr('src', $.data(this, 'src'));
  });
});

I'm not sure exactly what hover image you want, but the general approach is to store what it was originally and use than then restoring it on mouseleave. Or, just put the hover on the <img> itself, like this:

$(function() {
  $('.icon1 img').each(function(){
    $.data(this, 'src', this.src);
  }).hover(function(){
    this.src = 'otherImage.png';
  }).mouseout(function(){
    this.src = $.data(this, 'src');
  });
});


(function($) {  // private closure;  
    $(function() {  // document load;
        $('.icon1').hover(function(){
            $(this).find('img').attr('src', "recursos/botban/veh1.png");
        }, function(){
            $(this).find('img').attr('src', "recursos/botban/veh2.png");
        });
 });
})(jQuery);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜