英文:
Adding CSS class to selected item and updating other classes while there are same elements as the selected element
问题
我有一些与以下HTML代码相同的元素:
<ul class="nav-list">
<li>
<a href="#">
<i class="fa-solid fa-layer-group"></i>
<span class="links_name">My First Item</span>
</a>
</li>
</ul>
我想要在点击的项目上添加selected
类,并从所有其他相同类中删除该类。
我使用以下的jQuery代码仅向选定的ul
添加类:
$('.nav-list').click(function(){
$('.nav-list li a').removeClass('selected');
$(this).find('a').addClass('selected');
});
但是所有相同的元素都获取了特定的类。
解决方案是什么?
英文:
I have some same elements with the following HTML code:
<ul class="nav-list">
<li>
<a href="#">
<i class="fa-solid fa-layer-group"></i>
<span class="links_name">My First Item</span>
</a>
</li>
</ul>
I want to add selected
class to the clicked item and remove that class from all other same classes.
I use the following JQuery code to add a class to only selected ul
:
$('.nav-list').click(function(){
$('.nav-list li a').removeClass('selected');
$('.sidebar ul li a').addClass('selected');
});
But all the same elements get that specific class.
What is the solution?
答案1
得分: 1
设置监听器到锚元素,然后使用 "this" 关键字来访问被点击的元素并赋予它该类:
$('.nav-list li a').click(function () {
$(this).addClass('selected');
});
英文:
Set the listener to the anchor elements, then use the "this" keyword to access the clicked element and give it the class
$('.nav-list li a').click(function () {
$(this).addClass('selected');
});
答案2
得分: 0
尝试将事件监听器直接添加到子元素本身:
$('.nav-list').children().click(function(){
$(this).addClass('selected');
});
这样你可以直接选择被点击的元素。
英文:
Try adding the event listener directly to the child elements themselves:
$('.nav-list').children().click(function(){
$(this).addClass('selected');
});
So you directly can select the element clicked.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论