jQuery $(this).next()没有按预期工作

我正在尝试创建一个由hover事件触发的简单下拉列表。 为了节省编写代码,我想利用$(this)选择器,但是当我尝试将$(this)下一个’a’元素作为目标时,我一直遇到问题。 有没有人知道在使用$(this)选择器时对此进行编码的正确方法?

在下面的代码中,如果我将$(this).next(’a’)更改为$(’。base a’),代码工作正常但是我必须每次想要编写相同的jQuery代码块每次使用不同的类选择器使用此function。

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代码:

 

所以我也试过没有运气……任何想法:

 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))); 

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); }; 

尝试在您的hover函数中提供$(this)作为参数,然后将处理函数中的所有$(this)调用更改为参数:

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

而你的新function:

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

handlerOut相同的概念。

当你使用$(’。base a’)你没有下一个元素因为a嵌套在里面时,你应该使用$(this).children(’a’)代替。

 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);