2011-04-01 137 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')){ 
} 

的更好的辦法?

相關問題