我目前正在编写一个小脚本,但遇到了一个小问题。
我想定位 <a>
从具有与当前页面 URL 相同的 href-link 的列表中,并为其指定一个类。我得到了href
-已经部分了,但我不知道如何Tag
具体的<a>
与一个类。代码如下:
var url = window.location.pathname; // for example /somebody
var href = $('a').attr('href');
if (url == href) {
$('the Anchor with the right URL').addClass('myClass');
};
.myClass {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/somebody">Somebody</a>
<a href="/once">Once</a>
<a href="/told">Told</a>
<a href="/me">Me</a>
最佳答案
您可以使用更专业的选择器直接选择正确的链接。线索是您也可以在其中选择属性:
var url = '/somebody'; //window.location.pathname; // for example /somebody
var link = $( `a[href="${ url }"]` );
if (link) link.addClass('myClass');
.myClass {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/somebody">Somebody</a>
<a href="/once">Once</a>
<a href="/told">Told</a>
<a href="/me">Me</a>
关于javascript - 使用 jQuery 为与页面 URL 具有相同 href-link 的 anchor 元素提供一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52971160/