开发者

Problem with jQuery hover function

开发者 https://www.devze.com 2023-02-12 09:42 出处:网络
$(\'#element\').children(\'ul\').children(\'li\').children(\'a\').hover(function(){ var _this = $(this);
$('#element').children('ul').children('li').children('a').hover(function(){     
    var _this = $(this);
    _this.sibling开发者_如何学JAVAs('div').show();
},function(){
    _this.siblings('div').hide();
})

It works like it should, showing the div. but it will not hide it after. i guess _this isnt defined in the callbacl function. how do i pass it inside that function without having to select it again from the DOM? I think its a pretty basic javascript question, i just can´t figure it out.


You need this in both functions:

var _this = $(this);

But a little nicer way to do it is like this:

$('#element > ul > li > a').hover(function(e){ 
    $(this).siblings('div').toggle( e.type === 'mouseenter' );
});

...or if you were hoping to avoid multiple calls to .siblings(), you could do this:

$('#element > ul > li > a').each(function() {
    var $th = $(this);
    var sibs = $th.siblings('div');
    $th.hover(function(e){ 
        sibs.toggle( e.type === 'mouseenter' );
    });
});

FYI: When you do $(this), you're not selecting anything from the DOM. this is simply a direct reference to the element that is set for you when the handler is called.


In your example you pass two functions as arguments to the .hover() method, so any variables you declare inside the functions, are only available within the scope of that function. So if you need to use the _this variable in the second function, you need to declare it again.

But in your case, the intermediate variable should not be necessary, and you can omit it altogether:

$('#element').children('ul').children('li').children('a').hover(function(){ 
    $(this).siblings('div').show();
} ,function(){
    $(this).siblings('div').hide();
})


Why don't you use mouseenter and mouseleave?

Or maybe:

$('#element').children('ul').children('li').children('a').hover(function(){ 

    var _this = $(this);
    _this.siblings('div').show();

},function(){

    var _this = $(this);
    _this.siblings('div').hide();
})

The _this is "private" if i'm not mistaking in the first function statement...


If all of your links inside #element are inside li, you can call them using $('#element > a').hover().

Try this:

$('#element > a').mouseover(function () { $(this).siblings('div').show(); }).mouseout(function () { $(this).siblings('div').hide(); });

0

精彩评论

暂无评论...
验证码 换一张
取 消