我正在尝试创建由悬停事件触发的简单下拉菜单。为了节省编写代码,我想利用$(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)));
正确的想法,但是你把'var self = this'放在'handlerIn'的上下文之外(其中'this'实际上就是元素)。 – 2012-02-24 18:39:45
@ChrisPratt,是的,谢谢!代码没有被清晰地格式化,这总是导致我的这种错误。 – Joe 2012-02-24 18:57:07