将“this”传递给.on函数似乎不起作用

时间:2012-09-08 16:44:56

标签: javascript jquery

我有一个功能:

function test(e){
            $('.movie').find('.moreInfo').removeClass('moreInfoShow');
            e.parent().find('.moreInfo').addClass('moreInfoShow');
            $("#movieBox").isotope('reLayout');

            e.parent().find('.moreInfo').css("opacity", "0");
            e.parent().find('.moreInfo').animate({opacity: 1}, 500);
        }

由以下人员调用:

$("#movieBox").on('mouseover', '.moviePoster', function(event){test($(this));});

问题是我希望在页面加载时调用该函数。我需要将“this”传递给函数,但我没有运气让它工作。

这是我期望的工作:

test($(".moviePoster").first());

(所有代码都在“$(document).ready”函数中)

2 个答案:

答案 0 :(得分:1)

W / O小提琴:

改变这个:

$("#movieBox").on('mouseover', '.moviePoster', function(event){test($(this));});

$("#movieBox").on('mouseover', '.moviePoster', test);

然后$(this)里面的测试函数应该指向触发事件的jQuery对象。

使用“test($(this))”在回调中调用测试函数将立即执行该函数,而不是在事件被触发时。

更新

执行此操作后,您当然需要在页面加载时触发鼠标悬停事件。 请参阅Jashwant关于如何做到这一点的评论。

更新我错了。

function(event){test($(this));}

当然不会立即触发回调功能。只有在这样的情况下才会发生这种情况:

$("#movieBox").on('mouseover', '.moviePoster', test($(this)));

抱歉!

答案 1 :(得分:0)

如评论中所述,在页面加载时触发mouseover事件。

$("#movieBox").find('.moviePoster').trigger('mouseover');

Reference

相关问题