问题描述
我正在尝试创建一个由悬停事件触发的简单下拉列表。为了节省编写代码,我想利用$(this)选择器但是当我尝试将$(this)下一个'a'元素作为目标时,我一直遇到问题。有没有人知道在使用$(this)选择器时对此进行编码的正确方法?
I am attempting to create a simple dropdown that is triggered by a hover event. To save on writing code I want to take advantage of the $(this) selector but I keep running into a problem when I try to target $(this) next 'a' element. Does anyone know the correct way to code this while still using the $(this) selector?
在下面的代码中,如果我将$(this).next('a')更改为$('。base a'),代码工作正常,但我会每次我想使用不同的类选择器使用此功能时,必须编写相同的jQuery代码块。
In the below code if I change $(this).next('a') to $('.base a') the code works fine but then I would have to write the same block of jQuery code for each time I want to use this feature using a different class selector each time.
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 code:
HTML code:
<div id="info" class="base">
<a href="#" id="info-link" title=""></a>
<div id="expanded-info">
<!-- Stuff here -->
</div>
</div>
所以我也试过没有运气......任何想法:
So I also tried with no luck...any ideas:
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是函数作用域,而不是块作用域:
JavaScript is function scoped, not block scoped:
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);
};
这篇关于jQuery $(this).next()没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!