javascript - 基于url更新类

时间:2015-04-29 16:05:41

标签: javascript php jquery

  

!最新的我试过了。我把它放在我刚才包含的head.php中。如果您想亲自看到他们,我会发送我的文件。   我的文件夹目录

Main_Folder
-Main_files
-- JS_Folder
---- Js Files
-- Includes_Folder
---- Head.php is here


<script type="text/javascript">
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
//alert($('ul a').length);
$('ul a').each(function() { 
    if (this.href === path) {
        $(this).addClass('sub-menu active');
    }
    //alert(this.href);
});
}); 
</script>

整个侧栏:

 <div class="sidebar-scroll">
<div id="sidebar" class="nav-collapse collapse">
 <!-- BEGIN SIDEBAR MENU -->
  <ul class="sidebar-menu">
          <li class="sub-menu">
              <a class="" href="panel-admin.php">
                  <i class="icon-dashboard"></i>
                  <span>Dashboard</span>
              </a>
          </li>
          <li class="sub-menu">
              <a href="javascript:;" class="">
                  <i class="icon-briefcase"></i>
                  <span>Employees</span>
              </a>
          </li>
          <li class="sub-menu">
              <a href="javascript:;" class="">
                  <i class="icon-book"></i>
                  <span>Students</span>
              </a>
          </li>
          <li class="sub-menu">
             <a href="javascript:;" class="">
                  <i class="icon-calendar"></i>
                  <span>Scheduling</span>
                  <span class="arrow"></span>
              </a>
              <ul class="sub">
                  <li><a class="" href="admin-foreign.php">Foreign Languages</a></li>
                  <li><a class="" href="admin-esl.php">ESL Local</a></li>
                  <li><a class="" href="admin-workshop.php">Summer Workshops</a></li>
              </ul>
          </li>
          <li class="sub-menu">
              <a href="javascript:;" class="">
                  <i class="icon-pencil"></i>
                  <span>Enroll</span>
                  <span class="arrow"></span>
              </a>
              <ul class="sub">
                  <li><a class="" href="general.html">Foreign Languages</a></li>
                  <li><a class="" href="button.html">ESL Local</a></li>
                  <li><a class="" href="slider.html">Summer Workshops</a></li>
              </ul>
          </li>

      </ul>
 <!-- END SIDEBAR MENU -->

  

  需要

class="sub-menu"才能使下拉菜单丢弃。所以活动版本是class="sub-menu active"。如果是2级下拉菜单,则主条和子条都将设置为活动状态。

<小时/> <小时/>

这是我的旁边吧。

<div class="collapse navbar-collapse navbar-ex1-collapse">
        <ul class="nav navbar-nav side-nav">                    
            <li>
                <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>
            </li>
            <li>
                <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>
            </li>
        </ul>
    </div>

我已经尝试过以下方法,但没有一个适合我的情况:

Update class attribute based on page URL

https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/

  

第一个示例代码

$('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu

  var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename)

    if($(this).prop("href") == pagename){
        $('.menu li').removeClass("active"); // remove all active class    
        $(this).parent("li").addClass("active"); //put active in parent of <a> which is <li>
   }
});

在第一个菜单中,我已将菜单更改为collapse navbar-collapse navbar-ex1-collapsecollapse,但均无效。

  

在第二个示例代码中,我尝试了以下操作:

$(function() {
  $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
});

我放[2],因为我目前在localhost中。所以它会是localhost/folder_name/index.php

我也尝试过"/index.php"/但是当我点击它时会指示我localhost/index.php而不是localhost/folder_here/index.php

  

第三个示例代码

jQuery(function($) {
 var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
 $('ul a').each(function() {
  if (this.href === path) {
   $(this).addClass('active');
  }
 });
});

仍然无法运作。我已将$('ul a)更改为$('div ul a)$('div li ul a)

  

编辑:为了确保,创建的脚本仅包含在include('js/js_file.js');中。这行应该在加载html之前或之后?

     

正如David Thomas所建议的那样,我尝试了以下内容。但它没有用。

var url = 'window.location.pathname';
$('.nav a').each(function() {
  // get the absolute URL from the <a> element:
  var href = this.href,
    // get the current page and file-type:
    pageAndFile = href.split('/').pop();
  // if the location ends with the pageAndFile found in
  // the current <a> element (using String.prototype.endsWith())
  // we add the 'active' class-name:
  if (url.endsWith(pageAndFile)) {
    $(this).closest('li').addClass('sub-menu active');
  }
});

3 个答案:

答案 0 :(得分:1)

一种方法:

&#13;
&#13;
// obviously, use 'document.location'/'window.location' in the real thing:
var fakeLocation = 'http://www.example.com/index.php';

$('.nav a').each(function() {
  // get the absolute URL from the <a> element:
  var href = this.href,
    // get the current page and file-type:
    pageAndFile = href.split('/').pop();
  // if the location ends with the pageAndFile found in
  // the current <a> element (using String.prototype.endsWith())
  // we add the 'active' class-name:
  if (fakeLocation.endsWith(pageAndFile)) {
    $(this).closest('li').addClass('active');
  }
});
&#13;
.active {
  border: 1px solid red;
}
&#13;
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav side-nav">
    <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>

    </li>
    <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>

    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

JS Fiddle demo

对于那些不实施String.prototype.endsWith()的浏览器:

&#13;
&#13;
// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
  // creates a regular expression from the passed-in string, followed by the '$'
  // character which signifies that the passed-in string must be followed by the
  // end-of-string:
  var reg = new RegExp(testString + '$');

  // using RegExp.prototype.test() to test that the String we're testing,
  // the 'this,' is matched by the created regular expression:
  return reg.test(this);
};

var fakeLocation = 'http://www.example.com/index.php';

$('.nav a').each(function() {
  // get the absolute URL from the <a> element:
  var href = this.href,
    // get the current page and file-type:
    pageAndFile = href.split('/').pop();
  // if the location ends with the pageAndFile found in
  // the current <a> element (using String.prototype.endsWith())
  // we add the 'active' class-name:
  if (fakeLocation.endsWith(pageAndFile)) {
    $(this).closest('li').addClass('active');
  }
});
&#13;
.active {
  border: 1px solid red;
}
&#13;
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav side-nav">
    <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>

    </li>
    <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>

    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

JS Fiddle demo

而且,如果没有jQuery,你可以做同样的事情:

&#13;
&#13;
// simple shim for String.prototype.endsWith(), for browsers that
// don't yet implement the same:
String.prototype.endsWith = String.prototype.endsWith || function(testString) {
  var reg = new RegExp(testString + '$');
  return reg.test(this);
};

// again, in real-world non-demo use you should use 'document.location':
var fakeLocation = 'http://www.example.com/index.php',
  // finding the last portion of the fakeLocation variable:
  currentPage = fakeLocation.split('/').pop(),
  // getting all the a elements with an href attribute that ends
  // with the currentPage string (after escaping the special
  // characters with the (ugly) regular expression) and the
  // attribute-ends-with ('attribute$=value') selector:
  activeAElements = document.querySelectorAll('.nav a[href$=' + currentPage.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + ']');

// using Array.prototype.forEach to iterate over the array-like
// activeAElements NodeList:
Array.prototype.forEach.call(activeAElements, function(a) {
  // the first argument of the function is the array-element,
  // here an <a> element node;
  // we're adding the 'active' class-name to the parentNode of any <a>
  // element that was found by the above selector:
  a.parentNode.classList.add('active');
});
&#13;
.active {
  border: 1px solid red;
}
&#13;
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapse navbar-collapse navbar-ex1-collapse">
  <ul class="nav navbar-nav side-nav">
    <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a>

    </li>
    <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a>

    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

JS Fiddle demo

至于为什么你自己的尝试失败了:

$('.menu li a').each(function(){

  var pagename= location.pathname.split('/').pop();

    // the HTMLAnchorElement.href is the absolute URL formed
    // by the href attribute; to find the actual string from
    // an <a> element, you'd need to use either JavaScript:
    //  - this.getAttribute('href');
    // or jQuery's:
    //  - $(this).attr('href'); 
    if($(this).prop("href") == pagename){
        $('.menu li').removeClass("active");
        $(this).parent("li").addClass("active");
   }
});

你的第二次尝试:

$(function() {
  // this won't work because your JavaScript will return 'index.php',
  // and pass that into the attribute selector; unfortunately this
  // includes the period ('.'), which is a special character in CSS
  // and has to be double escaped, first for the JavaScript and then
  // the CSS
  $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active');
  // with that in mind, you'd need to do (something like) the following,
  // which - as in my own code - replaces all special characters with
  // a double-escaped version of that character (so '.' becomes '\\.'):
  $('nav a[href^="/' + location.pathname.split("/")[2].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '"]').addClass('active');
});

你的第三次尝试:

jQuery(function($) {
 var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
 $('ul a').each(function() {
  if (this.href === path) {
   $(this).addClass('active');
  }
 });
});

看起来它应该可行,尽管您正在向'active'元素添加(或应该添加)<a>类名,而不是祖先<li>元素

参考文献:

答案 1 :(得分:0)

假设location.pathname.split("/")[2]返回预期参数,问题是

$('nav a[href^="/'

应该是

$('.nav a[href^="'

.nav在您的示例中是一个类,而不是一个元素

答案 2 :(得分:0)

脚本中的问题......

$(function() {
    $('.nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');t
});