jQuery查找与当前页面匹配的链接 [英] jQuery find link that matches current page

查看:98
本文介绍了jQuery查找与当前页面匹配的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码试图找到与当前网址匹配的链接: $ item = $('ul#ui-ajax-tabs li a')。attr('href' ,$(location).attr('pathname')); 但它改变了当前网址的所有链接:P

I have the following code that is trying to find a link that matches the current url: $item = $('ul#ui-ajax-tabs li a').attr('href', $(location).attr('pathname')); but instead it changes all the links to the current url :P

可以任何人帮我解决它。干杯

Can anyone help me fix it. Cheers

推荐答案

使用此查询。您的代码更改了所选链接的所有 href 属性,而不是返回具有匹配 href 属性的链接选择:

Use this query. Your code changes all href attributes of the selected links, rather than returning a selection of links with a matching href attribute:

$("a[href*='" + location.pathname + "']")

[href * = ...] 选择器返回元素列表其 href 属性包含当前路径名。

The [href*=..] selector returns a list of elements whose href attribute contains the current pathname.

另一种方法,返回 href的所有元素包含当前路径名。使用 prop()代替 attr(),以便正确解释相对URL。

Another method, return all elements whose href contains the current pathname. prop() is used instead of attr(), so that relative URLs are also correctly interpreted.

$item = $('ul#ui-ajax-tabs li a').filter(function(){
    return $(this).prop('href').indexOf(location.pathname) != -1;
});

这篇关于jQuery查找与当前页面匹配的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆