2010-04-12 8 views
1

jQuery를 사용하여 간단한 작업을 수행하려고합니다. 마우스 커서를 놓을 때 해당 이미지가 사라져야하는 단어 목록이 있습니다. 예를 들어 :jQuery selective hover

<a href="#" class="yellow">Yellow</a> 
<a href="#" class="blue">Blue</a> 
<a href="#" class="green">Green</a> 

<img src="yellow.jpg" class="yellow"> 
<img src="blue.jpg" class="blue"> 
<img src="green.jpg" class="green"> 

나는 현재 각 링크/이미지에 대해 이런 식으로 일을 해요 :

$('a.yellow').hover(
    function() { 
    $('img.yellow').fadeIn('fast'); 
    }, 
    function() { 
    $('img.yellow').fadeOut('fast'); 
    }); 

방법은 위의 잘 작동하지만 난 아직 배우는 중이에요으로, 나는 거기에 더 나은 것 같아요 방법을 반복하는 대신에 그것을 할 수 있습니다.

아무도 나에게 약간의 빛을 줄 수 있습니까? 이 코드를 어떻게 향상시킬 수 있습니까?

답변

4
<a href="#" class="yellow" data-type="color">Yellow</a> 
<a href="#" class="blue" data-type="color">Blue</a> 
<a href="#" class="green" data-type="color">Green</a> 

jQuery를 코드

$('a[data-type=color]').hover(
    function() { 
    $('img.'+$(this).attr("class")).fadeIn('fast'); 
    }, 
    function() { 
    $('img.'+$(this).attr("class")).fadeOut('fast'); 
    }); 
}); 

난 당신이 하나를 시도해야한다고 생각. html5를 준수하기 때문에 사용자 정의 속성의 접두어로 data-을 사용했습니다. 원하는 경우 data-something이라고 말할 수 있습니다.

일반적으로 데이터 색상 맞춤 속성을 사용할 필요는 없지만 좀 더 일반적인 것으로 생각하기 때문에 그 속성을 사용했습니다. 당신은뿐만 아니라 이러한 코드를 수행 할 수 있습니다

<a href="#" class="yellow">Yellow</a> 
<a href="#" class="blue">Blue</a> 
<a href="#" class="green">Green</a> 

그런 다음

$('a').hover(
    function() { 
    $('img.'+$(this).attr("class")).fadeIn('fast'); 
    }, 
    function() { 
    $('img.'+$(this).attr("class")).fadeOut('fast'); 
    }); 
}); 

그러나이 방법, 당신은 모든 링크가 이미지 관련 링크되어 있는지 확인해야한다.

+0

와우, 정말 고마워! 여기에서 잘 작동합니다. – Vitor

2
<a href="#" id="yellow" class="colorLink">Yellow</a> 
<a href="#" id="blue" class="colorLink">Blue</a> 
<a href="#" id="green" class="colorLink">Green</a> 

<img src="yellow.jpg" class="yellow"> 
<img src="blue.jpg" class="blue"> 
<img src="green.jpg" class="green"> 

$("a.colorLink").hover(
    function(){ 
     $("img."+this.id).fadeIn('fast'); 
    }, 
    function(){ 
     $("img."+this.id).fadeOut('fast'); 
    } 
); 

이렇게하면 이미지에 해당하는 각 링크에 고유 한 ID가 설정됩니다.