HTML页面有一个无序列表,我们希望每当点击任何列表项时,背景颜色应该如下改变: 假设列表l1,l2,l3中有三个项目 当用户单击l1时,
$('.nav').on('click', 'li', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});

li.active {
background-color: red;
color: #000;
cursor: default;
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Header</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<header>
<div>
<ul class="nav">
<li>Home</li>
<li>Tutorials</li>
<li>About</li>
<li>Newsletter</li>
<li>Contact</li>
</ul>
</div>
</header>
</body>
</html>
&#13;
答案 0 :(得分:1)
您需要在HTML内容之后(在正文结束之前)移动脚本,或者需要将您的JS代码包装在DOMReady事件中,如评论中提到的@BenM。
您可以参考以下工作示例:
使用DOMReady事件:
li.active {
background-color: red;
color: #000;
cursor: default;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function() {
$('.nav').on('click', 'li', function() {
$('.nav li').removeClass('active');
$(this).addClass('active');
});
});
</script>
<header>
<div>
<ul class="nav">
<li>Home</li>
<li>Tutorials</li>
<li>About</li>
<li>Newsletter</li>
<li>Contact</li>
</ul>
</div>
</header>
&#13;
最后移动脚本:
li.active {
background-color: red;
color: #000;
cursor: default;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<div>
<ul class="nav">
<li>Home</li>
<li>Tutorials</li>
<li>About</li>
<li>Newsletter</li>
<li>Contact</li>
</ul>
</div>
</header>
<script>
$('.nav').on('click', 'li', function() {
$('.nav li').removeClass('active');
$(this).addClass('active');
});
</script>
&#13;
答案 1 :(得分:1)
格式正确
根据DOM jquery
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Header</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
li.active {
background-color: red;
color: #000;
cursor: default;
}
</style>
</head>
<body>
<header>
<div>
<ul class="nav">
<li>Home</li>
<li>Tutorials</li>
<li>About</li>
<li>Newsletter</li>
<li>Contact</li>
</ul>
</div>
</header>
<script>
$(function(){
$('.nav').on('click', 'li', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
})
</script>
</body>
</html>