当前位置: 动力学知识库 > 问答 > 编程问答 >

css - jQuery adding a class to an li href using a hash?

问题描述:

I'm trying to code some jQuery to check if a link in my unordered list is the current page that is being viewed and then to add a class of "current" to that list item.

This is the code I am currently using:

$(document).ready(function() {

//<![CDATA[

jQuery(function() {

jQuery('.sidebar li').each(function() {

var href = jQuery(this).find('a').attr('href');

if (href === window.location.pathname) {

jQuery(this).addClass('current');

}

});

});

//]]>

});

This works to an extent, but because all of the links in my sidebar are hashes, it always sets the current class on the first li. For example here is what my links look like:

<ul>

<li><a href="/posts#page1" />Table of Contents</a></li>

<li><a href="/posts#page10" />Chapter 1</a></li>

<li><a href="/posts#page25" />Chapter 2</a></li>

</ul>

In this example, the current class is only applied to the "Table of Contents" li, even if you are on a different page.

Is it possible to accomplish what I'm trying in this way?

Thanks!

网友答案:

Just append location.hash to the pathname. It will be empty if there is none so it will work that way for links without one.

if (href === window.location.pathname + window.location.hash) {
分享给朋友:
您可能感兴趣的文章:
随机阅读: