根据URL设置活动链接 [英] Set active link based on URL

查看:91
本文介绍了根据URL设置活动链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果URL结束:?style=product我想将active类添加到li类中的product

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

HTML:

<ul id="menulist">
  <li class="product">Product</li>
  <li class="product2">Product 2</li>
  <li class="product3">Product 3</li>
</ul>

推荐答案

您可能应该与Andy一起在服务器端进行渲染,但是要回答您的问题,这是您应该在javascript/jQuery中实现相同功能的方法(如果(例如,没有服务器端)

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)

如果您可以对url进行很多假设(肯定会始终使用该查询字符串,那么它将始终是 first ),肯定有更简单的方法来获取样式"查询字符串.查询字符串,将永远不会有任何 other 查询字符串,在查询字符串之后绝对不会有任何 hash 数据.).如果您不能做出这样的假设,以下可能是最安全的方法.

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');
}

请注意,我假设您还希望product2成为active,以防您的URL以style=product2结尾.如果在选择product要应用此效果,则必须将最后一个条件调整为

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');
}

编辑

将上述选择内容编辑为使用window.location.search,以采纳Andy的建议,该建议可防止location.hash.

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

这篇关于根据URL设置活动链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆