jQuery在页面加载时将活动类添加到父级

时间:2016-05-07 10:48:04

标签: javascript php jquery

enter image description here (所有孩子都活跃,如图所示) 我想在点击子项时将class =“active”添加到父项。我设法将“活动”类添加到父级,但所有子级也添加了class =“active”。我想要的只是被选中的孩子,其父母是“活跃的”。

Jquery的:

$(document).ready(function(){
var pathname = window.location.pathname;
var filename=pathname.replace(/^.*[\\\/]/, '');

var currentLink=$('a[href="' + filename + '"]'); //Selects the proper a tag
currentLink.parents('.doctormenu').find('li a').removeClass('active'); 
currentLink.parentsUntil('.doctormenu', 'li').addClass('active'); 
//currentLink.parent().addClass("active");
//alert(filename);
})   

HTML:

<ul class="doctormenu">
  <li><a href="index.html" class="active">home</a></li>
  <li><a href="testabout.php">about</a></li>
  <li><a href="testdisease.php">Disease</a></li>
  <li><a href="login.html">Search</a></li>




  <li><a href="#" >
  Services</a>
  <ul>
  <li><a href="asdqq.html">Self Diagnosis</a></li>
  <li><a href="testservice.php">Online Consultation</a></li>
  <li><a href="#">Clinic Appointment</a></li>
  </ul>
  </li>
  </ul>

2 个答案:

答案 0 :(得分:1)

 $('.doctormenu li a').each(function(){
        // and test its normalized href against the url pathname regexp
        if(urlRegExp.test(this.href.replace(/\/$/,''))){
            $(this).parent().addClass('active');
        }
    });

答案 1 :(得分:0)

这里有fiddle并附有正确的演示

重要的代码是:

// you can change this on.hashchange for the on.documentready
$(window).on('hashchange', function () {
  // select a reference, in your case can be the pathname or whatever
  var ref = location.hash
  // find the matching element
  var $el = $('a[href="' + ref + '"]')
  // and it's closest parent (avoid select other 
  // parents and it's less risky than .parent)
  var $menu = $el.closest('.doctormenu')

  // remove previous active, if there's any 
  // (may you don't need this if the page is reloading)
  $('.doctormenu')
    .removeClass('active')
    .find('a')
    .removeClass('active')

  // execute the needed operations, adding class in this example
  $el.addClass('active')
  $menu.addClass('active')
});