开发者

How to give two functions to delegate function

I'm using JQuery and trying to use delegate for the hover action. Problem is the hover action can get two handlers, the handle in and the handle out. How can I achieve this using delegate?

I开发者_如何学编程've tried this and it didn't work:

 $(document).delegate('.box', 'hover',  
    function() { $(".a").addClass(".hover");}, 
    function() { $(".a").removeClass(".hover");});


According to the docs for .hover:

$(selector).mouseenter(handlerIn).mouseleave(handlerOut);

So you should be able to just call delegate once for each of these functions:

$(document)
  .delegate('.box', 'mouseenter', function() { alert(1); })
  .delegate('.box', 'mouseleave', function() { alert(2); });


An alternative to @Justin's solution is to check the event type in the callback:

function onMouseenter()
{
    alert(1);
}
function onMouseleave()
{
    alert(2);
}

$(document).delegate('.box', 'hover', function(event)
{
    if (event.type === 'mouseenter') onMouseenter.apply(this, arguments);
    else onMouseleave.apply(this, arguments);
});

That said, it's unnecessary to use .delegate() if you're just going to delegate to document. Use .live() instead, which is much more concise:

$('.box').live('hover', function (event)
{
    // snip...
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜