问题
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?
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 code:
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:
<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)));
回答1:
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);
};
回答2:
Try supplying $(this)
as a parameter in your hover
function and then changing all your $(this)
calls in your handler functions to the parameter:
$(".base").hover(handlerIn($(this)), handlerOut($(this)));
And your new functions:
function handlerIn( elem ){
elem.next('a')
.fadeIn(); // or whatever you plan on doing with it
}
Same concept with handlerOut
.
回答3:
When you use $('.base a') you don't have a next element because a is nested inside, you should use $(this).children('a') instead.
回答4:
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);
来源:https://stackoverflow.com/questions/9436093/jquery-this-next-not-working-as-expected