2012-02-24 76 views
3

我正在尝试创建由悬停事件触发的简单下拉菜单。为了节省编写代码,我想利用$(this)选择器,但当我尝试以$(this)为目标的下一个'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

JavaScript是功能范围的,不区块范围:

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'实际上就是元素)。 – 2012-02-24 18:39:45

+0

@ChrisPratt,是的,谢谢!代码没有被清晰地格式化,这总是导致我的这种错误。 – Joe 2012-02-24 18:57:07

0

尝试提供$(this)在你hover函数中的参数,然后改变你的所有$(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')时,您没有下一个元素,因为嵌套在里面,您应该使用$(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);