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>