代码中的问题是什么不起作用,我也检查了其他方法,但仍然是同样的问题。
$('li a').click(function() {
$('a').removeClass('active');
$(this).addClass('active');
});
.active
{
text-decoration: none;
color: #03B003;
background-color: red;
}
<ul class="nav-list">
<li>
<a href="/portfolio">Portfolio</a>
</li>
<li>
<a href="/work">Projects</a>
</li>
<li>
<a href="/resume">Resume</a>
</li>
</ul>
答案 0 :(得分:2)
为什么不使用CSS的:active属性。 a:active {做某事;} 这个简单的代码不需要jQuery
答案 1 :(得分:0)
这是没有jQuery的普通JS的实现方法
fn search<'a>(word: &str, data: &'a [String]) -> Vec<&'a String> {
data.iter().filter(|x| x.contains(word)).collect()
}
// Get all elements
var urls = document.getElementsByClassName('url');
// Make sure there are elements
if( urls )
{
// For each element
for( var i = 0; i < urls.length; i++ )
{
var url = urls[i];
// Add an event to a element
url.addEventListener( 'click', function(e) {
// Check if a class is already set on a element and peform action based on that
if( e.target.classList.contains( 'active' ) )
{
e.target.classList.remove( 'active' );
} else {
e.target.classList.add( 'active' );
}
});
}
}
.active
{
text-decoration: none;
color: #03B003;
background-color: red;
}
或者只为每个页面设置活动类:
<ul class="nav-list">
<li>
<a href="#" class="url">Portfolio</a>
</li>
<li>
<a href="#" class="url">Projects</a>
</li>
<li>
<a href="#" class="url">Resume</a>
</li>
</ul>
.active
{
text-decoration: none;
color: #03B003;
background-color: red;
}
答案 2 :(得分:0)
这里是代码,它应在您的情况下起作用,但仅当您的网址带有'/ something'时才有效。为了更好地尝试自己修改;)
$(function() {
var currentPage = window.location.href;
var urlParts = currentPage.split('/');
var searchFor = '/' + urlParts[urlParts.length - 1];
$('.nav-list a').each(function() {
if ($(this).attr('href') == searchFor) {
$(this).addClass('active');
}
});
});