如何为这段代码添加活动选择器

任何人都可以帮助我添加一个活动的选择器,以便当点击一个链接时,该链接将收到不同的颜色背景或者可能只是加粗吗?

 

这实际上很容易实现,并且基于您在其他post中的2条评论中提到的内容 ,您重新加载每个链接的页面,并且url在示例“oneplus”链接中,例如“ https:/” /www.oneplus.com/support “ ,只需1行脚本即可设置。

通过简单地检测页面何时加载( .ready() ),您可以获取当前window.location并使用其pathname属性。

结合属性selector attribute="value" ,您可以在链接中添加一个类,这是推荐的方式,以下是它在代码中的外观

 $( document ).ready(function() { $('.link-leftbar[href$="' + window.location.pathname + '"]').addClass('active'); }); 

在上面我用( $ )selector [attr$="value"] 结尾 ,但是如果你的url变得更复杂,还有更多变种,你可以在这个链接属性选择器中查看它们。

由于每次页面加载时都会调用此函数,因此它也适用于页面刷新。

如果您开始使用例如Ajax来加载内容,只需执行此行,它就会设置您的活动链接。

 $('.link-leftbar[href$="' + window.location.pathname + '"]').addClass('active'); 

下面是一个示例,我在其中手动设置了url,并且还显示了如何更改内联CSS,如果由于任何原因无法使用类。

还要注意,因为将li包裹在任何其他元素中但是作为ul的子元素是无效的,我将ul / li更改为下面示例中的div / span ,并添加了其他样式以使链接垂直堆叠并且具有子弹。

堆栈代码段

 var window_location = new URL("http://https://stackoverflow.com/questions/51157267/how-can-i-add-an-active-selector-to-this-piece-of-code/www.test.com/support/international"); $(document).ready(function() { // using a class, recommended $('.link-leftbar[href$="' + window_location.pathname + '"]').addClass('active'); // change inline CSS, if you can't use classes $('.link-leftbar[href$="' + window_location.pathname + '"]').css('color', 'darkblue'); }); 
 .active { font-weight: bold; } /* additional styling - */ .link-leftbar span { /* - stack links vertically */ display: block; } .link-leftbar span::before { /* - add a bullet to each */ content: '•'; padding: 0 10px 0 25px; display:inline-block; }