Javascript 使用YUI将类添加到当前活动链接
我在jQuery中得到了这个函数:Javascript 使用YUI将类添加到当前活动链接,javascript,yui,Javascript,Yui,我在jQuery中得到了这个函数: 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'); } }); }); 但不幸的是,我需要用YU
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元素添加一个类
非常感谢 以上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');
});
但是,我可以想象你可以这样做:
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');
});
达到同样的效果。(仅在我的头脑中测试代码)另一种选择:
YUI().use('node', function(){
Y.all('.primary-nav li').each(function(node){
var href = node.getAttribute('href');
node.toggleClass('current', href === window.location.pathname);
});
});
如果第二个参数为true,则添加该类,否则将删除该类