2011-04-01 106 views
1

什么类型的元素,我使用下面的模块来显示一个子菜单:如何判断事件被触发的

icisSite.fatNav = function(trigger){ 

    function init() { 
     width = 0, 
     $mainMenuListEl = $('.nav-SiteNav .nav-list > li'), 
     $subNav = $('.subNav > li > ul'); 
     appendSubNav(); 
     getWidth(); 
    }; 

    function appendSubNav(){ 
     $subNav.each(function(index){ 
      index = ++index; 
      $(this).appendTo($mainMenuListEl[index]); 
     });  
    }; 

    function subNavShow(trigger){ 
     setWidth(trigger); 
     trigger.toggleClass('hover'); 
    }; 

    function subNavHide(trigger){ 
     trigger.toggleClass('hover'); 
     trigger 
     .find('ul') 
     .removeAttr('style'); 
    }; 

    function getWidth(){ 
     $mainMenuListEl.each(function(index){ 
      width += parseInt($(this).outerWidth()); 
     }); 

     width = width - 11; 
    }; 

    function setWidth(trigger){ 
     trigger 
     .find('ul') 
     .css({'width': width}); 
    }; 

    return { 
     setup: init, 
     show: subNavShow, 
     hide: subNavHide 
    }; 

}(); 

icisSite.fatNav.setup(); 

$('.nav-SiteNav .nav-list > li:gt(0)').hover(function() { 
    $this = $(this); 
    icisSite.fatNav.show($this);  
},function(e) { 
    icisSite.fatNav.hide($this); 
}); 

$('.nav-SiteNav .nav-list > li:gt(0) a').focusin(function() { 

    var $this = $(this); 

    $this 
    .parent() 
    .toggleClass('hover'); 

    $this 
    .parent() 
    .find('ul') 
    .css({'width': icisSite.width}); 

}); 

$('.nav-SiteNav .nav-list > li:gt(0) a').focusout(function() { 

    var $this = $(this); 

    $this 
    .parent() 
    .toggleClass('hover'); 

    $this 
    .parent() 
    .find('ul') 
    .removeAttr('style'); 

}); 

我想重构,以适应的focusIn和focusOut事件。由于代码与悬停事件非常相似,但并不相同。

我不确定如何做到这一点,而不是检查“触发”的元素类型,并想知道是否有更好的方法?

我甚至不知道如何检索元素的类型吗?所以如果是悬停,它会返回一个li元素和一个焦点锚元素。

回答

4

如果你想测试一个jQuery对象是你可以简单地使用.is()

if($(this).is('li')){ 
} 

if($(this).is('a')){ 
} 

而且,你也许可以重构你的focusIn,事件的内容部分以及通过检查event.type

没有测试,但可能会是这个样子......

$('.nav-SiteNav .nav-list > li:gt(0) a').bind("focusin, focusout", function(event) { 
    var $this = $(this); 
    $this 
    .parent() 
    .toggleClass('hover'); 

    $this 
    .parent() 
    .find('ul'); 

    if(event.type =="focusout"){ 
    $this.removeAttr('style'); 
    } 
    else 
    { 
    $this.css({'width': icisSite.width}); 
    } 
}); 
+0

谢谢。认为我在某种程度上过度复杂化了这个问题。 – RyanP13 2011-04-01 10:58:24

1

岂不

$(this).get(0).tagName 

得到好标签的类型,而不是去

if($(this).is('li')){ 
} 

的更好的办法?

相关问题