基于 anchor link 的状态变化 - 在加载时有效,但如果 anchor 改变则不行?

Change of state based on anchor link - works on load, but not if anchor changes?

我正在为我自己的发展做一个个人项目,我无法解决我的问题。

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

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

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

试试,

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');
  } );
});