将CSS类添加到所选项目,并在存在与所选元素相同的元素时更新其他类。

huangapple go评论52阅读模式
英文:

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:

&lt;ul class=&quot;nav-list&quot;&gt;
    &lt;li&gt;
        &lt;a href=&quot;#&quot;&gt;
            &lt;i class=&quot;fa-solid fa-layer-group&quot;&gt;&lt;/i&gt;
            &lt;span class=&quot;links_name&quot;&gt;My First Item&lt;/span&gt;
        &lt;/a&gt;
    &lt;/li&gt;
&lt;/ul&gt;

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:

$(&#39;.nav-list&#39;).click(function(){
    $(&#39;.nav-list li a&#39;).removeClass(&#39;selected&#39;);
    $(&#39;.sidebar ul li a&#39;).addClass(&#39;selected&#39;);
});

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

 $(&#39;.nav-list li a&#39;).click(function () {
  $(this).addClass(&#39;selected&#39;);
 });

答案2

得分: 0

尝试将事件监听器直接添加到子元素本身:

$('.nav-list').children().click(function(){
    $(this).addClass('selected');
});

这样你可以直接选择被点击的元素。

英文:

Try adding the event listener directly to the child elements themselves:

$(&#39;.nav-list&#39;).children().click(function(){
    $(this).addClass(&#39;selected&#39;);
});

So you directly can select the element clicked.

huangapple
  • 本文由 发表于 2023年2月18日 02:44:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定