.removeClass()未删除类.可能的特异性错误

.removeClass() not removing class. Possible specificity error

本文关键字:特异性 错误 删除 removeClass      更新时间:2023-09-26

我试图同时向单击的链接添加一个类,同时从DOM中删除同一个类。代码中添加类的部分是有效的,但它只是让类一次又一次地出现。我也很好奇javascript解决方案与服务器端解决方案的有效性。

$(document).ready(function() {
    $(function() {
    $('#header a span').click(function(e) {
    var title = this.innerText; 
    //possible browser compatability from .text?
        $('selected').removeClass('selected');
        $(this).addClass('selected');
        // Also prevent the link from being followed: 
    });
    });
<div id="header" class="ui-corner-all ui-buttonset">
         <a title="index" href="#" class="link" ><span>home</span></a>
         <a title="code" href="#" class="link" ><span>code</span></a>
         <a title="design" href="#" class="link" ><span>design</span></a>
         <a title="illustration" href="#"class="link" ><span>illustration</span></a>
         <a title="writing" href="#" class="link" ><span>writing</span></a>
         <a title="links" href="#" class="selected" ><span>links</span></a>
         <a title="about" href="#" class="selected"><span>about</span></a>
         </div>

将JS更改为:

$(document).ready(function() {
    $('#header a span').click(function(e) {
       var title = $(this).text();
       //possible browser compatability from .text?
        $('.selected').removeClass('selected');
        $(this).addClass('selected');
        // Also prevent the link from being followed: 
        return false;
    });
});

顺便说一下,你想让你的类selectedspan元素上,还是在a元素上,你的JS表示span,而你的html表示a

$('selected').removeClass('selected');

应该是

$('.selected').removeClass('selected');

我想你的类需要(.)。