[英]Javascript - How to highlight the last clicked list item
I have a sidebar list of items in HTML on a bootstrap page and i would like the last clicked item to be highlighted with a "active" class. 我在引导页面上有HTML项的侧边栏列表,我希望最后单击的项以“活动”类突出显示。 I was wondering how i can get the whole list (ul) like an array so i could highlight a certain item (li) or highlight the last clicked item.
我想知道如何像数组一样获取整个列表(ul),以便突出显示某个项目(li)或突出显示最后单击的项目。
The list is structured like this: 该列表的结构如下:
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar sidebar-style">
<ul class="nav nav-sidebar sidebar-scrollable">
<li class="active"><a href="#" onclick="jump(0)">Home</a></li>
<li><a href="#" onclick="jump(1)">Site 001</a></li>
<li><a href="#" onclick="jump(2)">Site 002</a></li>
<li><a href="#" onclick="jump(3)">Site 003</a></li>
<li><a href="#" onclick="jump(4)">Site 004</a></li>
<li><a href="#" onclick="jump(5)">Site 005</a></li>
What i need is some JS code which can set the last clicked li item to class="active" but still have the option to set any of the li items to the active one, for example if i wanted to have a random button and it selected item 4 then 2 etc. I guess the main thing i need is a way to have all list items like an array. 我需要的是一些JS代码,可以将最后单击的li项设置为class =“ active”,但仍然可以选择将任何li项设置为active项,例如,如果我想要一个随机按钮,选择项目4然后2等。我想我主要需要的是一种使所有列表项都像数组一样的方法。
I strongly suggest you use jQuery which is kind of simulating DOM manipulation like an array or more precisely an object. 我强烈建议您使用jQuery,它是一种类似于数组或对象的DOM模拟DOM操作。
My suggestion would be the following: 我的建议如下:
$(".nav-sidebar").on('click', 'li', function(e) {
$(this).parent().find('li.active').removeClass('active');
$(this).addClass('active');
});
This code is removing the active class from all li
items, and adding active class to currently clicked li
item. 此代码是从所有
li
项目中删除活动类,并将活动类添加到当前单击的li
项目中。
Cheers, 干杯,
Edit PS: 编辑PS:
You could also bind your event directly like this: 您还可以像这样直接绑定事件:
$(".nav-sidebar li").click(...);
But the purpose of using .on()
is that it will bind the event dynamically, so that if you decide to add a new li to your $(".nav-sidebar")
element, it will also trigger the event on that element. 但是,使用
.on()
的目的是它将动态绑定事件,因此,如果您决定向$(".nav-sidebar")
元素添加新li,它也会触发该元素上的事件。
Edit: 编辑:
To answer @zeddex your question: How to select manually li 4? 要回答@zeddex,您的问题是:如何手动选择li 4? You simply use the following:
您只需使用以下内容:
$("li:eq(3)").trigger('click');
That'll manually trigger a click event for li 4. If you want to select a specific li you can use a method of the like: :eq(x)
in which x
is the position of the li item you want to reach starting from 0
which corresponds to your first li
. 这将手动触发li 4的click事件。如果要选择特定的li,则可以使用以下方法
:eq(x)
,其中x
是您要从以下位置到达li项目的位置0
对应于您的第一个li
。 Have a look at jQuery DOC on that: jQuery DOC on :eq() 看一下jQuery DOC ::eq()上的jQuery DOC。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.