Set active link based on URL

后端 未结 6 1843
猫巷女王i
猫巷女王i 2021-01-29 05:58

If the URL ends: ?style=product I want to add a class of active to the li with the class of product

HTML:

<         


        
6条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 06:23

    You should probably go with Andy and render this serverside, but to answer your question, this is what you should do to achieve the same in javascript/jQuery (if, say, there is no server-side)

    There are definitely easier ways of getting the 'style' querystring, if you can make a lot of assumptions about the url (that it will always have that querystring, that it will always be the first querystring, that there will never be any other querystrings, that there will never be any hash data after the querystring...). The below is probably the safest way to go if you cannot make such assumptions.

    var activeStyle = '';
    
    if(window.location.search != '') {
       // find querystring section or url
       var query = window.location.search.substring(1);
    
       // split querystring into key/value-pairs
       query = query.split('&');
    
       for(var i = 0; i < query.length; i++) {
    
           // split key/value pair into key and value
           var keyvalue = query[i].split('=');
    
           // find value of ?style=
           if(keyvalue[0].toLowerCase() == 'style')) {
              activeStyle = keyvalue[1];
              break;
           }
       }
    }
    
    if(activeStyle != '') {
       $('li.' + activeStyle).addClass('active');
    }
    

    Note that I assumed that you also want product2 to become active in case your URL ends in style=product2. If you only want to apply this effect when product is selected, you would have to adjust the last condition to

    if(activeStyle.toLowerCase() == 'product') {
        $('li.product').addClass('active');
    }
    

    EDIT

    Edited the above selection to use window.location.search instead, to pick up on Andy's advice, which guards against location.hash.

提交回复
热议问题