Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery将活动类添加到navbar不起作用_Javascript_Jquery - Fatal编程技术网

Javascript jQuery将活动类添加到navbar不起作用

Javascript jQuery将活动类添加到navbar不起作用,javascript,jquery,Javascript,Jquery,因此,我没有使用HTML将活动类添加到导航栏,而是希望通过jQuery添加它,但我的代码似乎不起作用 $('.navbar-nav li a[href="' + location.pathname + '"]').addClass('active'); 有人能帮我吗?也许你可以这样做: $(function() { var currentLoc = window.location.href; if(/PageYouWant/.test(currentLoc) {

因此,我没有使用HTML将活动类添加到导航栏,而是希望通过jQuery添加它,但我的代码似乎不起作用

$('.navbar-nav li a[href="' + location.pathname + '"]').addClass('active');


有人能帮我吗?

也许你可以这样做:

$(function() {
  var currentLoc = window.location.href;
  if(/PageYouWant/.test(currentLoc) {
    $('.navbar-nav li a').addClass('active');
  }
});
var pathname =  window.location.href;
$('.navbar-nav li a').attr('href',pathname).addClass('active');

我想你需要的是window.location.href。 大概是这样的:

$(function() {
  var currentLoc = window.location.href;
  if(/PageYouWant/.test(currentLoc) {
    $('.navbar-nav li a').addClass('active');
  }
});
var pathname =  window.location.href;
$('.navbar-nav li a').attr('href',pathname).addClass('active');

选中此示例:

如果要在锚定标记中设置活动,可以执行以下选项之一

  • 将ID分配给每个a标记
  • a指定一个数据属性并添加一个类toggleClassX
  • 使用$(this.addClass(“活动”)
  • 以下是每个建议的示例:

    1 html:

    <nav> 
       <ul class="navbar-nav">
         <li class="nav-item" >
           <a class="nav-link active" id="myId1" href="">Home</a>
        </li> 
        <li class="nav-item">
          <a class="nav-link" id="myId2" href="">Wat is het?</a>
        </li>
      </ul>
    </nav>
    
    2 js:

    3 js:

    $(".nav-link").click(function(){
     $(this).addClass("active")
    });
    

    希望以上回答您的问题。

    location.pathname
    提供当前页面的路径,例如
    /foo/bar/index.html
    。您拥有的
    href
    属性中没有一个与Ijzeredraak5匹配,空链接的含义是什么?当然,OP不希望这样,因为他只想为当前页面的链接添加类。@MoshFeu感谢您的澄清。我已经更新了我的答案。但是,它仍然不起作用,因为它将为菜单中的所有链接添加类。
    $(".nav-link").click(function(){
     $(this).addClass("active")
    });