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

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

Adding CSS class to selected item and updating other classes while there are same elements as the selected element

问题

我有一些与以下HTML代码相同的元素:

  1. <ul class="nav-list">
  2. <li>
  3. <a href="#">
  4. <i class="fa-solid fa-layer-group"></i>
  5. <span class="links_name">My First Item</span>
  6. </a>
  7. </li>
  8. </ul>

我想要在点击的项目上添加selected类,并从所有其他相同类中删除该类。
我使用以下的jQuery代码仅向选定的ul添加类:

  1. $('.nav-list').click(function(){
  2. $('.nav-list li a').removeClass('selected');
  3. $(this).find('a').addClass('selected');
  4. });

但是所有相同的元素都获取了特定的类。
解决方案是什么?

英文:

I have some same elements with the following HTML code:

  1. &lt;ul class=&quot;nav-list&quot;&gt;
  2. &lt;li&gt;
  3. &lt;a href=&quot;#&quot;&gt;
  4. &lt;i class=&quot;fa-solid fa-layer-group&quot;&gt;&lt;/i&gt;
  5. &lt;span class=&quot;links_name&quot;&gt;My First Item&lt;/span&gt;
  6. &lt;/a&gt;
  7. &lt;/li&gt;
  8. &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:

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

But all the same elements get that specific class.
What is the solution?

答案1

得分: 1

设置监听器到锚元素,然后使用 "this" 关键字来访问被点击的元素并赋予它该类:

  1. $('.nav-list li a').click(function () {
  2. $(this).addClass('selected');
  3. });
英文:

Set the listener to the anchor elements, then use the "this" keyword to access the clicked element and give it the class

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

答案2

得分: 0

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

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

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

英文:

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

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

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:

确定