开发者

Passing variable in jQuery through bind doesn't seem to work

Here's my code that does work:

function mouseOver()
{
    $(".beaver").fadeIn(100);

}

function mouseOut()
{
    $(".beaver").fadeOut(100);
}

$("#group_beaver").bind('mouseenter', mouseOver).bind('mouseleave', mouseOut);

But why doesn't this work?

function mouseOver(variable)
{
    $(variabl开发者_开发问答e).fadeIn(100);

}

function mouseOut(variable)
{
    $(variable).fadeOut(100);
}

$("#group_beaver").bind('mouseenter', mouseOver('.beaver')).bind('mouseleave', mouseOut('.beaver'));


That's correct; you're calling mouseOver and expecting it to return a function to be bound to the event. To make it actually do that, though, you can use this code:

function mouseOver(variable) {
    return function() {
        $(variable).fadeIn(100);
    };
}
function mouseOut(variable) {
    return function() {
        $(variable).fadeOut(100);
    };
}


icktoofay's technique is called a closure. There's an excruciatingly comprehensive discussion of closures here. I find them super useful for scheduling events with window.setTimeout(). They basically allow you to load up a function object with preconditions and then evaluate it with no arguments. Pretty nifty.

However for all their novelty closures can usually be avoided. For instance, if .beaver's are children of #group_beaver you would be better off with something like

function mouseOver()
{
    $(this).children().fadeIn(100);
}

In event handlers jQuery makes sure that this always refers to the element that triggered the event, so you've basically got an argument for free. Given the simplicity of your example I'm guessing a closure is not necessary.

You could also do:

$('group_beaver').mouseenter(function() {
    $(variable).fadeIn(100);
});

Which is really just a closure in disguise. Its the same as writing:

function mouseOver(variable) {
    return function() {
        $(variable).fadeIn(100);
    }
};

$('#group_beaver').mouseenter(mouseOver('.beaver'));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜