基于锚链接的状态变化 - 对负载起作用,但是如果锚更改则不起作用?

问题描述 投票:1回答:1

我正在为自己的发展工作一个个人项目,为了我的生活,我无法解决我的问题。

我的问题:如果地址栏中的#anchor变量是'this',请添加该类。这方面工作正常,但如果单击一个按钮并更改锚点,则类不会自行应用。如何通过代码修改状态的变化?任何想法或建议表示赞赏。

我尝试了各种组合,但下面的组合最接近我的目标?

jQuery(function($) {
  var path = location.href;
  $('li a').each(function() {
    if (this.href === path) {
      $(this).addClass('current-link');
    }
  });
});
javascript jquery wordpress if-statement anchor
1个回答
0
投票

尝试,

jQuery(function($) {
  var path = location.href;
  $('li a').each(function() {
    if (this.href === path) {
      $(this).addClass('current-link');
    }
  });

  // Add this code
  $('li a').click( function() {
    $( this ).parents('ul').find('.current-link').removeClass('current-link');
    $( this ).addClass('current-link');
  } );
});
© www.soinside.com 2019 - 2024. All rights reserved.