2014-12-02 106 views
-5

如何点击使用jQuery添加和删除类?我需要其他类别不受影响。使用jQuery添加和删除类

所以,当你点击.other-class.one它变成.other-class.two。如果你点击.other-class.two它会变成.other-class.one。

这就是我迄今为止的第二次JS加载工作。

<p class="other-class one">Trigger</p> 
.one { 
    background: red; 
} 
.two { 
    background: blue; 
} 
.other-class { 
    text-decoration: underline; 
} 
$('.one').click(function(){ 
    $(this).removeClass('one'); 
    $(this).addClass('two'); 
}); 

$('.two').click(function(){ 
    $(this).removeClass('two'); 
    $(this).addClass('one'); 
}); 
+0

为什么这个问题有这么多downvotes? – musefan 2014-12-02 11:04:53

+0

我想说这个问题唯一不好的地方在于,OP没有明确提及JS的第二次加载不起作用。究竟发生了什么,不应该发生? – musefan 2014-12-02 11:11:09

回答

5

您需要使用event delegation

$('body').on('click','.one',function(){ 
$(this).removeClass('one').addClass('two'); 
}); 

$('body').on('click','.two',function(){ 
$(this).removeClass('two').addClass('one'); 
}); 
2

在这种情况下,你可以使用toggleClass(),但作为一个正常的解决方案,这种动态选择场景你应该使用event delegation

$('.one, .two').click(function() { 
 
    $(this).toggleClass('one two'); 
 
});
.one { 
 
    background: red; 
 
} 
 
.two { 
 
    background: blue; 
 
} 
 
.other-class { 
 
    text-decoration: underline; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<p class="other-class one">Trigger</p>


为什么?因为在正常情况下委托模型的选择进行评估,只有当执行登记代码,以便在您的实例中,仅第一个处理程序被添加到p元素一度让你点击多少次,只执行第一处理

2
$(body).on('click', '.other-class' function() { 
    $(this).toggleClass('one two'); 
}); 
0

我假设你正在寻找切换效果。您可以将事件分配给“普通”类,然后切换。像这样:

$('.other-class').click(function(){ 
    if($(this).hasClass('one')) 
     $(this).removeClass('one').addClass('two'); 
    else 
     $(this).removeClass('two').addClass('one'); 
}); 

Here is a working example