简体   繁体   English

主动点击链接

[英]Active li on link click

i'm trying to apply a selected/active effect on my tabs. 我正在尝试在选项卡上应用选定的/活动的效果。 So when a tab is selected it should apply the active class on it and by default the first tab is the active class. 因此,选择一个选项卡后,应在其上应用活动类,默认情况下,第一个选项卡是活动类。 I've tried with a jquery function but not seem to work: 我已经尝试过使用jQuery函数,但似乎无法正常工作:

jsfiddle: http://jsfiddle.net/8thrh/82/ jsfiddle: http : //jsfiddle.net/8thrh/82/

 $(function() { $('#nav').find('a').click(function(e) { e.preventDefault(); $(this.hash).show().siblings().hide(); }).filter(':first').click(); }); $('a').on('click',function(){ $('li').removeClass('active'); $(this).addClass('active'); }); 
 #nav li { display: inline-block; padding: 10px 11px; background: #fff !important; margin-right: 6px; } #nav ul { } #nav li a { color: #000; text-decoration: none; text-transform: uppercase; } .active { background: #000000 !important; color: #fff; } 
 <ul id="nav"> <li><a href="#part-1">Leage of Legends</a></li> <li><a href="#part-2">CS:GO</a></li> <li><a href="#part-3">Dota2</a></li> <li><a href="#part-3">Hearthstone</a></li> </ul> <div id="content"> <div id="part-1"> Ma première partie </div> <div id="part-2"> Ma deuxième partie </div> <div id="part-3"> Ma troisième partie </div> </div> 

There's no need for two different click bindings: 不需要两个不同的单击绑定:

$(function() {
   $('#nav').find('a').click(function(e) {
       e.preventDefault();
       $(this.hash).show().siblings().hide();
       $('#nav').find('a').parent().removeClass('active')
       $(this).parent().addClass('active')
   }).filter(':first').click();
});

http://jsfiddle.net/9c2kxz09/1/ http://jsfiddle.net/9c2kxz09/1/

Also the CSS is wrong; CSS也错了; nav li background cannot be made !important , it'll override the active class. 无法设置nav li background !important ,它将覆盖active类。

I cleaned up the css: http://jsfiddle.net/9c2kxz09/4/ 我清理了CSS: http : //jsfiddle.net/9c2kxz09/4/

$('a').click(function() {
   $('a').removeClass('active');
    $(this).addClass('active');
});

Thats the basic outline for the jQuery click event. 这就是jQuery click事件的基本轮廓。 Amend as necessary but ensure you are removing and adding the class to the same element. 根据需要进行修改,但确保要删除该类并将其添加到同一元素。 Hope this helps :) 希望这可以帮助 :)

The primary issue is that in your fiddle, you are including jQuery 1.6, a very old version. 主要的问题是,在您的小提琴中,您包括了非常老的jQuery 1.6。 Include 1.9.1 at least. 至少包括1.9.1。

$('a').on('click',function(){
     $('li a').removeClass('active');
     $(this).addClass('active');
}).first().click();

http://jsfiddle.net/8thrh/87/ http://jsfiddle.net/8thrh/87/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM