Для селектора атрибута в jQuery вы должны использовать атрибут, за которым следует $
. Взгляните на селектор атрибутов do c Jquery
Я также внес изменения в следующий блок. Пожалуйста, проверьте фрагмент.
$('#toc li a').removeClass('active');
$('a[href$="'+id+'"]').addClass('active');
Также добавьте $('li:first-child').children().addClass('active');
в конце или .each()
, чтобы добавить активный класс к первому элементу.
var $ = jQuery;
$(document).ready(function() {
$("#toc").append(' ')
$("h2").each(function(i) {
var current = $(this);
current.attr("id", "title" + i);
$("#toc").append(`<li><a id="link${i}" href="#title${i}" title="${current.attr("tagName")}">${current.html()}</a></li>`);
});
$('li:first-child').children().addClass('active'); // Add this to add active class only on first item
});
$(window).on('scroll', function() {
$('h2').each(function() {
if($(window).scrollTop() >= $(this).offset().top) {
var id = $(this).attr('id');
$('#toc li a').removeClass('active');
$('a[href$="'+id+'"]').addClass('active');
}
});
});
h2 {
border-bottom: 1px dotted #000;
color: #000;
margin-top: 1.5rem;
}
#toc{
color: #000;
list-style: none;
margin: 0, 0, 0;
}
#toc li {
margin: 1rem 0.2rem 0;
color: #000;
}
#toc li a{
color: #000;
font-family: Calibri, Sans-sarif;
font-weight: bold;
font-size: 16px;
cursor: pointer;
text-decoration: none;
list-style: none;
}
#toc li a:hover, #toc a.active {
background: #666;
color: #000;
}
.nav-container{
position: fixed;
left: 0px;
width: 160px;
height: 180px;
padding-top: 0px;
}
.container{
margin-left: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<nav class="nav-container">
<ul id="toc"></ul>
</nav>
<div class="container">
<h2>Test1</h2>
<p>This is a test</p>
<p>This is a test</p>
<h2>Test2</h2>
<p>TLSDGn lsjdlgjsldj gljlsdjgljlsdjgljdsl gjldfjgljdfljgldjflkgj ldfjgljldfjgl jldfg</p>
<p>This is a test</p>
<p>This is a another test</p>
<p>This is a another another another test</p>
<h2>Test3</h2>
<p>This is a test</p>
<p>This is a test</p>
<h2>Test4</h2>
<p>TLSDGn lsjdlgjsldj gljlsdjgljlsdjgljdsl gjldfjgljdfljgldjflkgj ldfjgljldfjgl jldfg</p>
<p>This is a test</p>
<p>This is a another test</p>
<p>This is a another another another test</p>
<h2>Test5</h2>
<p>This is a test</p>
<p>This is a test</p>
<h2>Test6</h2>
<p>TLSDGn lsjdlgjsldj gljlsdjgljlsdjgljdsl gjldfjgljdfljgldjflkgj ldfjgljldfjgl jldfg</p>
<p>This is a test</p>
<p>This is a another test</p>
<p>This is a another another another test</p>
</div>
</body>
</html>