2014-04-30 59 views
0

當前激活鏈接我jQuery中得到這個功能:類添加到使用YUI

jQuery(function() { 
    jQuery('.primary-nav li').each(function() { 
    var href = jQuery(this).find('a').attr('href'); 
    if (href === window.location.pathname) { 
    jQuery(this).addClass('current'); 
    } 
    }); 
}); 

但不幸的是我需要做的完成同樣與YUI庫。如果a href與當前活動頁面相同,則向a元素添加一個類。

非常感謝!

回答

0

以上的JQuery的幾乎直接翻譯會是這樣的:

YUI().use('node', function(){ 
    Y.all('.primary-nav li').each(function(node){ 
     var href = node.getAttribute('href'); 
     if (href === window.location.pathname){ 
      node.addClass('current'); 
     } 
    }); 
}); 

不過,我會想象你可以這樣做:

YUI().use('node', function(){ 
    Y.one('.primary-nav li a[href="' + window.location.pathname + '"]').addClass('current'); 
}); 

要達到同樣的效果。 (代碼在我的頭只測試)

1

一種替代:

YUI().use('node', function(){ 
    Y.all('.primary-nav li').each(function(node){ 
     var href = node.getAttribute('href'); 
     node.toggleClass('current', href === window.location.pathname); 
    }); 
}); 

添加類別中,如果第二個參數爲真,否則刪除它。