jQuery在Selected选项卡上添加类

我是jQuery的初学者,我正在尝试修改脚本。 脚本演示在这里 。 现在,他们在所选标签上方添加一行,我不想要。 我想要做的只是添加一个类到锚点

Tab Name 

这样我就可以使用CSS来改变活动按钮的背景颜色或其他东西。

以下代码是您单击选项卡时的当前代码。

 the_tabs.click(function(e){ /* "this" points to the clicked tab hyperlink: */ var element = $(this); /* If it is currently active, return false and exit: */ if(element.hasClass('.active')) return false; $(this).addClass('active') 

 the_tabs.click(function(e){ var element = $(this); if( element.hasClass('active') ) { return false; } else { the_tabs.removeClass('active'); element.addClass('active'); } } 

您只需要:

  $(this).addClass('nameOfYourClass') 

向被单击的对象添加一个类

代替

 if(element.find('.active').length) return false; 

使用

 if(element.hasClass('.active')) return false; 

或者您必须使用.filter而不是.find ,find正在尝试查找具有.active类的子节点但.filter过滤掉该集合以找到匹配的css-selecotr

试试这个:

 the_tabs.click(function(e){ /* "this" points to the clicked tab hyperlink: */ var element = $(this); /* If it is currently active, return false and exit: */ if(element.hasClass('active')) return false; /* Detecting the color of the tab (it was added to the class attribute in the loop above): */ var bg = element.attr('class').replace('tab ',''); $('ul.tabContainer .active').removeClass('active'); element.addClass('active'); /* Checking whether the AJAX fetched page has been cached: */ if(!element.data('cache')) { /* If no cache is present, show the gif preloader and run an AJAX request: */ $('#contentHolder').html(''); $.get(element.data('page'),function(msg){ $('#contentHolder').html(msg); /* After page was received, add it to the cache for the current hyperlink: */ element.data('cache',msg); }); } else $('#contentHolder').html(element.data('cache')); e.preventDefault(); }) 

另请查看我的博客(网站)以获取一些不错的jQuery指南。 🙂