2012-02-24 4 views
3

호버 이벤트에 의해 트리거되는 간단한 드롭 다운을 만들려고합니다. 코드 작성시 절약하려면 $ (this) 선택기를 활용하고 싶지만 $ (this) next 'a'요소를 대상으로 할 때 문제가 계속 발생합니다. 누구든지 $ (this) 선택기를 사용하면서 코드를 작성하는 올바른 방법을 알고 있습니까?

$ (this) .next ('a')를 $ ('. base a')로 변경하면 코드가 제대로 작동하지만 각 jQuery 코드의 동일한 블록을 작성해야합니다. 시간마다 다른 클래스 선택기를 사용하여이 기능을 사용하고 싶습니다.

jQuery 코드 :

var handlerIn = function() { 
var t = setTimeout(function() { 
     $(this).next('a') <==== Problem is here 
     .addClass('active') 
     .next('div') 
     .animate({'height':'show'}, {duration:'slow', easing: 'easeOutBounce'}); 
}, 400); 
$(this).data('timeout', t); 
} ; 

var handlerOut = function() { 
clearTimeout($(this).data('timeout')); 
$(this).next('a') <==== Problem is here 
    .removeClass('active') 
    .next('div') 
    .slideUp(); 

}; 

$('.base').hover(handlerIn, handlerOut); 

HTML 코드 :

<div id="info" class="base"> 
<a href="#" id="info-link" title=""></a> 
     <div id="expanded-info"> 
       <!-- Stuff here -->    
     </div> 
</div> 
그래서

나는 또한 행운과 함께 시도 ... 어떤 아이디어 :

var handlerIn = function(elem) { 
var t = setTimeout(function() { 
     $(elem).next('a') 
     .addClass('active') 
     .next('div') 
     .animate({'height':'show'}, {duration:'slow', easing: 'easeOutBounce'}); 
}, 400); 
$(elem).data('timeout', t); 
} ; 

var handlerOut = function(elem) { 
clearTimeout($(elem).data('timeout')); 
$(elem).next('a') 
    .removeClass('active') 
    .next('div') 
    .slideUp(); 

}; 
$('.base').hover(handlerIn($(this)), handlerOut($(this))); 

답변

2

자바 스크립트, 함수는 범위가 아니다 차단 범위 :

var handlerIn = function() { 
    var self = this; 
    var t = setTimeout(function() { 
     $(self).next('a') 
      .addClass('active') 
      .next('div') 
      .animate({'height':'show'}, {duration:'slow', easing: 'easeOutBounce'}); 
     }, 400); 
    $(this).data('timeout', t); 
}; 
+0

'var self = this'는 'handlerIn' ('this '는 실제로 동작하는 요소입니다)의 컨텍스트 외부에 배치했습니다. –

+0

@ChrisPratt, 네, 고마워요! 코드는 명확하게 형식화되지 않았으므로 항상 이러한 종류의 실수가 발생합니다. – Joe

0

에 한번 당신의 hover 함수에서 매개 변수로 $(this)을 공급하고 매개 변수에 핸들러 함수에 모든 $(this) 통화를 변경 :

$(".base").hover(handlerIn($(this)), handlerOut($(this))); 

그리고 당신의 새로운 기능 :

function handlerIn(elem){ 
    elem.next('a') 
     .fadeIn(); // or whatever you plan on doing with it 
} 

동일한 개념 handlerOut.

0

$ ('. base a')를 사용할 때 a가 안에 중첩되어 있기 때문에 다음 요소가 없으므로 대신 $ (this) .children ('a')을 사용해야합니다.

0
var handlerIn = function() { 
    var $base = $(this); 
    var t = setTimeout(function() { 
     $base.next('a') 
      .addClass('active') 
      .next('div') 
      .animate({'height':'show'}, {duration:'slow', easing: 'easeOutBounce'}); 
    }, 400); 
    $base.data('timeout', t); 
}; 

var handlerOut = function() { 
    var $base = $(this); 
    clearTimeout($base.data('timeout')); 
    $base.next('a') 
     .removeClass('active') 
     .next('div') 
     .slideUp(); 

}; 

$('.base').hover(handlerIn, handlerOut); 
관련 문제