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

时间:2012-02-24 18:31:23

标签: jquery this

我正在尝试创建一个由悬停事件触发的简单下拉列表。为了节省编写代码,我想利用$(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 code:

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

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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

你的新功能:

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

handlerOut相同的概念。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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