点击后的活动链接 [英] Active link after click

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

问题描述

我无法找到将类添加到导航栏的a元素的方法。

这是html nav和jQuery(仅适用于test.html网址,用于测试它):

<

  $(document).ready(function(){$(a)。click(function(){var actRef = $ (this).attr(href); if(actRef ===test.html){$(a [href ='test.html'])。addClass(active);}}) ;});  

 < script src =https: //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script><nav> < UL> < li>< a href =index.html> Inicio< / a> < /锂> < li>< a href =test.html>测试< / a> < /锂> < li>< a href =#>商品< / a> < /锂> < li>< a href =test2.html> TEST2< / A> < /锂> < / nav>  

,它只是不做任何事情,但如果我将.click改为.hover,它可以很好地添加类,但不会去链接,所以页面的信息不会改变。

我也试过这个: 如何更改活动类,而点击另一个链接引导使用jquery?,但既不是因为 e.preventDefault(); ...



如果我拿出preventDefault它不会添加类,但它会转发到链接...



PD:目标是让用户根据他点击的菜单链接知道他实际上在哪个标签上。

解决方案

感谢@Panther这比我想的更容易:

  $(document).ready(function(){
var location = window.location.pathname;
location = location.replace(/, );
$(a [href ='+ location +')。addClass(active);
});


I cant find a way to add a class to an "a" element of a nav bar.

This is the html nav and the jQuery (applied to test.html url only, to test it):

$(document).ready(function() {
  $("a").click(function() {
    var actRef = $(this).attr("href");
    if (actRef === "test.html") {
      $("a[href='test.html']").addClass("active");
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<nav>
  <ul>
    <li><a href="index.html">Inicio</a>
    </li>
    <li><a href="test.html">Test</a>
    </li>
    <li><a href="#">Item</a>
    </li>
    <li><a href="test2.html"> test2</a>
    </li>
  </ul>
</nav>

This isnt working, it just doesnt do anything, but if i change the .click to .hover it works fine adding the class but doesnt go to the link so the info of the page wont change.
I also tried this: How to change active class while click to another link in bootstrap use jquery? but neither works because of the e.preventDefault();...

If i take out the preventDefault it wont add the class but it will forward to the link...

PD: The aim is to let the user know on which tab he is actually on depending on the menu link he clicked.

解决方案

Thanks to @Panther this is easier than i tought:

$(document).ready( function(){
var location = window.location.pathname;
location = location.replace("/", "");
$("a[href='"+location+"']").addClass("active");
});

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

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