且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

点击后的活动链接

更新时间:2022-12-19 18:54:29

感谢@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");
});