jQuery live和delegation可能无法在插件中运行?

时间:2011-02-18 16:25:24

标签: jquery

$.fn.tool = function(sel){
    this.each(function(){
        $this=$(this);
        $this.live('mouseover mouseout',function(e){
            if(e.type=='mouseover')
            {
                $this.find(sel).show();
            }
            else
            {
                $this.find(sel).hide();
            }
        });
    });
}

我想在鼠标悬停在元素的容器上时显示元素。该插件不会。

2 个答案:

答案 0 :(得分:1)

jQuery delegates with plugins 它可能会对你有帮助。

在你的插件中,你不必使用事件委托,这取决于使用插件的人。

答案 1 :(得分:1)

您在.live()上呼叫$(this),这意味着它正在丢失它所需的原始选择器。

由于不需要为每个元素分配多个.live()处理程序,只需执行以下操作:

$.fn.tool = function(sel){
    return this.live('mouseover mouseout',function(e){
        if(e.type=='mouseover') {
            $(this).find(sel).show();
        } else {
            $(this).find(sel).hide();
        }
    });
}