JQ implementation switch menu selection state

Time:2020-1-16

Click the navigation menu to switch the selected state

Effect:

 

 

 

 

Idea: first, get the selected URL, and then judge whether it is the same through regular. If it is the same, add the corresponding attribute, and if it is different, remove the corresponding attribute.

HTML code

home page
            
        
        
            
                
                video
            
        
        
            
                
                Music
            
        
        
            
                
                dynamic
            
        
        
            
                
                about
            
        
    


<span style="background-color: #f5f5f5; color: #800000;">
    .active</span><span style="background-color: #f5f5f5; color: #000000;">{</span><span style="background-color: #f5f5f5; color: #ff0000;">
        color</span><span style="background-color: #f5f5f5; color: #000000;">:</span><span style="background-color: #f5f5f5; color: #0000ff;"> red
    </span><span style="background-color: #f5f5f5; color: #000000;">}</span>

JQ code

var url = location.href;
    $('.item > a').each(function () {
        pat = new RegExp('/index/index/index');
        if (pat.test(url)){
            $('.item>a').eq(0).addClass('active');
            $('.item>a>img').eq(0).attr("src","/public/index/images/icon/home_selected.png");
        }
        pat = new RegExp('/index/index/videos');
        if (pat.test(url)){
            $('.item>a').eq(0).removeClass('active');
            $('.item>a').eq(1).addClass('active');
            $('.item>a>img').eq(1).attr("src","/public/index/images/icon/video_selected.png");
        }
        pat = new RegExp('/index/index/music');
        if (pat.test(url)){
            $('.item>a').eq(1).removeClass('active');
            $('.item>a').eq(2).addClass('active');
            $('.item>a>img').eq(2).attr("src","/public/index/images/icon/music_selected.png");
        }
        pat = new RegExp('/index/index/news');
        if (pat.test(url)){
            $('.item>a').eq(2).removeClass('active');
            $('.item>a').eq(3).addClass('active');
            $('.item>a>img').eq(3).attr("src","/public/index/images/icon/new_selected.png");
        }
        pat = new RegExp('/index/index/about');
        if (pat.test(url)){
            $('.item>a').eq(3).removeClass('active');
            $('.item>a').eq(4).addClass('active');
            $('.item>a>img').eq(4).attr("src","/public/index/images/icon/about_selected.png");
        }
    });