jQuery查找与当前页面匹配的链接
我有以下代码试图找到与当前url匹配的链接: $item = $('ul#ui-ajax-tabs li a').attr('href', $(location).attr('pathname'));
但它改变了当前url的所有链接:P
任何人都可以帮我解决它。 干杯
使用此查询。 您的代码更改了所选链接的所有href
属性,而不是返回具有匹配href
属性的链接选择:
$("a[href*='" + location.pathname + "']")
[href*=..]
选择器返回其href
属性包含当前路径名的元素列表。
另一种方法,返回其href
包含当前路径名的所有元素。 prop()
代替attr()
,以便正确解释相对URL。
$item = $('ul#ui-ajax-tabs li a').filter(function(){ return $(this).prop('href').indexOf(location.pathname) != -1; });
那是因为你的CSS选择器ul#ui-ajax-tabs li a
匹配多个东西。 尝试使用您的选择器更具体,例如ul#ui-ajax-tabs li:first-child a
。
其中URL格式可能会像ASP.NET一样在生产中更改:/如果忽略URL的结束斜杠,这可能会更好。
$('.mdl-navigation').find("a").filter(function () { return this.href.replace(/\/+$/, '') === window.location.href.replace(/\/+$/, ''); }).addClass('current-active-page-url');