我有一个选择器,它将“活动”类添加到所选页面。
但是,它仅适用于斜杠,例如如果它是:

Site.com/TEST/,效果很好。

但是,如果没有它的Site.com/TEST。

使用“返回”按钮时,这会引起问题,因为它会将我带回到页面,但没有尾随的“ /”

这是我的代码:

$(document).ready(function () {
    $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
});


有人可以对此进行修改以将课程添加到两种版本中吗?
另外,如果可以的话,如果我选择父级的子页面,是否可以对其进行修改,以便将活动类添加到父级?

例如。 Site.com/Test/Edit我想将测试设置为活动状态。

谢谢

最佳答案

str.replace(/\/+$/,'') + '/'将始终确保字符串以/结尾,因此您的代码应如下所示:

$(document).ready(function () {
    str = this.location.pathname.replace(/\/+$/,'') + '/';
    $('a[href="' + str + '"]').parent().addClass('active');
});


如果您不知道所有链接是否都以斜杠结尾,则可以检查所有内容:

$(document).ready(function () {
    str1 = this.location.pathname.replace(/\/+$/,'') + '/';
    str2 = this.location.pathname.replace(/\/+$/,'');
    $('a[href="' + str1 + '"], a[href="' + str2 + '"]').parent().addClass('active');
});


编辑

让我们尝试选择所有父链接:

var tmp = this.location.pathname.replace(/.*?:\/\//g, "").replace(/\/+$/,'');
arr = tmp.split('/');
while(arr.length > 1) {
  tmp = 'http://' + arr.join('/');
  $('a[href="' + tmp + '"], a[href="' + tmp + '/"]').parent().addClass('active');
  arr = arr.slice(0,-1);
}


基本上,我从一开始就删除了http://并将字符串拆分为每个/上的数组元素。然后,我一个接一个地删除末端元素,再次将其粘合,并相应地构造选择器。

它在起作用,它如何生成链接:



$('#test').click(function(){

  // I replaced the string with the input value for testing
  var tmp = $('input').val().replace(/.*?:\/\//g, "").replace(/\/+$/,'');
  arr = tmp.split('/');

  // Clearing the output here
  $('div').html('');
  while(arr.length > 1) {
    tmp = 'http://' + arr.join('/');

    // Appending the current result
    $('div').append('<p>' + tmp + '/</p>');
    $('a[href="' + tmp + '"], a[href="' + tmp + '/"]').parent().addClass('active');
    arr = arr.slice(0,-1);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input value="http://google.com/sub1/sub2">
<button id="test">test</button>
<div></div>

关于java - 将 Activity 类添加到所选页面(带斜线和不带斜线),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31290499/

10-15 03:42