jQuery addClass不会将类添加到元素(jQuery addClass doesn't add class to element)

编程入门 行业动态 更新时间:2024-10-10 04:26:57
jQuery addClass不会将类添加到元素(jQuery addClass doesn't add class to element)

我有以下的HTML代码

<ul class='selectul'> <li class='active'><a href='?sortby=views'>by Popularity.</a></li> <li><a href='?sortby=recency'>by Recency.</a></li> <li><a href='?sortby=alphabet'>Alphabetically.</a></li> </ul>

当任何<li>元素被点击时,我想为其添加class='active' 。 没有一个兄弟姐妹可以参加这个班。 我试图用下面的jQuery代码来做到这一点

(function(){ $('.selectul li').on('click',function(){ $(this).addClass('active'); $(this).siblings().removeClass('active'); }); }())

但它似乎没有做任何事情。 我刚刚开始使用jQuery,所以我很抱歉如果这个问题是相当基本的。

I've the following html code

<ul class='selectul'> <li class='active'><a href='?sortby=views'>by Popularity.</a></li> <li><a href='?sortby=recency'>by Recency.</a></li> <li><a href='?sortby=alphabet'>Alphabetically.</a></li> </ul>

When any <li> element is clicked, I want to add class='active' to it. None of its siblings is then allowed to have this class. I tried to do this with the following jQuery code

(function(){ $('.selectul li').on('click',function(){ $(this).addClass('active'); $(this).siblings().removeClass('active'); }); }())

but it doesn't seem to do anything. I'm just getting started with jQuery so I apologize if this question is rather basic.

最满意答案

剧本是好的。 问题在别的地方。 一旦你点击链接,文件重新加载,你不会注意到类的变化。

尝试:

(function(){ $('.selectul li').on('click',function(){ $(this).addClass('active'); $(this).siblings().removeClass('active'); return false; }); }());

返回false将中断Click-Event并阻止重新加载文档。

The script is all right. The problem is somewhere else. Once you click the link, the document reload and you do not notice the change of classes.

Try:

(function(){ $('.selectul li').on('click',function(){ $(this).addClass('active'); $(this).siblings().removeClass('active'); return false; }); }());

return false interrupts the Click-Event and prevent the reload of the document.

更多推荐

本文发布于:2023-07-09 10:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085503.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:会将   元素   addClass   jQuery   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!