【问题标题】:Img attr src will not changeimg attr src 不会改变
【发布时间】:2012-11-14 04:30:49
【问题描述】:

这是我能够在悬停 src 时显示的情况,但屏幕上的图像本身并没有实际改变。任何帮助都会有很大帮助。

$('.hoverImgs').hover(
function(){mouseOn = 1; formSelector('hover');},
function(){mouseOn = 0; formSelector('out');
});

function formSelector(method){
if(mouseOn === 1 && method === 'hover'){       
    $(this).attr("src", "images/radio_hover.png");
    alert($(this).attr("src"));
}
else {}
}
});

【问题讨论】:

  • this 在你的函数中没有任何 jQuery 上下文。它是窗口

标签: jquery src attr


【解决方案1】:

当您调用函数formSelectorthis 时上下文丢失了函数内的窗口对象。您应该将this 对象作为参数传递或使用.call/.apply 调用函数。

尝试如下,

$(function () {
   var mouseOn;
   $('.hoverImgs').hover(
      function(){ mouseOn = 1; formSelector('hover', this); },
      function(){mouseOn = 0; formSelector('out', this); }
   );

  function formSelector(method, thisObj){
     if(mouseOn === 1 && method === 'hover'){       
       thisObj.src = "images/radio_hover.png";
       alert(thisObj.src);
     }
     else {}
   }

});

【讨论】:

    【解决方案2】:

    首先,您在末尾有一个额外的});

    你真正的问题:this 不是你想的那样。在这种情况下,this 指的是窗口对象,而不是图像。解决此问题的一种方法是将图像元素传递给函数。

    $('.hoverImgs').hover(
      function(){mouseOn = 1; formSelector($(this), 'hover');},
      function(){mouseOn = 0; formSelector($(this), 'out');}
    );
    
    function formSelector(elem, method){
      if(mouseOn === 1 && method === 'hover'){
        console.log(elem.attr('src'));
        elem.attr("src", "https://www.google.com/images/srpr/logo3w.png");
      }
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多