2012-11-14 3 views
2

Heres 님이 chenged로 src를 가리킬 수 있지만 화면 자체의 이미지가 실제로 변경되지 않습니다. 어떤 도움이 큰 도움이 될 것입니다.Img attr 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 {} 
} 
}); 
+0

는'.. 그것은 창에게 무리 파트너가 매력처럼 작동 – charlietfl

답변

2

당신이 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 {} 
    } 

}); 
+0

감사합니다! –

2

첫째, 아래와 같이하십시오.

당신의 진짜 문제 : this는 당신이 생각하는 것과 다릅니다. 이 컨텍스트에서 this은 이미지가 아니라 창 개체를 나타냅니다. 이 문제를 해결하는 한 가지 방법은 image 요소를 함수로 전달하는 것입니다. 함수의 모든 jQuery를 컨텍스트가없는 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

관련 문제