Jquery问题onclick添加类和删除类
第一次在这里发帖。我是 jquery 的初学者,我遇到了一些灰色区域。希望我能在这里找到答案并从中学习:)
所以我有一个比方说10个不同的div。所有人都有相同的班级。每次我单击 div 时,它都必须添加另一个类(在本例中是 css 中的背景颜色)。为此,我有这样的:
$(document).ready(function() {
$(".menucardmenu").click(function(){
if($(this).hasClass("menucardmenu")) {
$(this).addClass("backgroundmenucard");
}
else {
alert ("condition false");
}
});
});
但现在的问题是,我怎样才能使只有一个 div 可以具有该背景颜色(在我的例子中是backgroundmenucard)。根据用户单击的 div,该 div 将具有背景颜色,并且前一个 div(被单击的)应将其重置回正常状态。我可以用这个做吗?:
$(this).removeClass("backgroundmenucard");
有谁知道这个问题的答案吗???
问候, 安德鲁
first time posting here. I'm a beginner in jquery and i ran into some grey area. Hopefully i can find my answer here and learn from it also :)
So i have a let's say 10 different div. All has the same class. And everytime I click on the div it has to add another class (in this case background-color in css). For that I have this:
$(document).ready(function() {
$(".menucardmenu").click(function(){
if($(this).hasClass("menucardmenu")) {
$(this).addClass("backgroundmenucard");
}
else {
alert ("condition false");
}
});
});
But the question now is, how can i make that only one div can have that background-color (in my case backgroundmenucard). Depending one which div the user click, that div will have the background-color, and the previous div (that was clicked) should reset it back to normal. I can do it with this right?:
$(this).removeClass("backgroundmenucard");
does anyone know the answer to this???
Regards,
Andrew
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试以下操作:
演示: http://jsfiddle.net/r2Sua/
(我删除了
if
因为在这种情况下它没有用)try the following:
Demo: http://jsfiddle.net/r2Sua/
(I remove the
if
because it's useless in this case)从所有中删除...
然后添加到
this
Remove from all...
Then add to
this
if($(this).hasClass("menucardmenu"))
检查完全没有必要,因为您已经选择了具有该类的元素。它将始终评估为true
。The
if($(this).hasClass("menucardmenu"))
check is completely unnecessary since you're already selecting elements which have that class. It will always evaluate totrue
.另一种选择是:
这样您就不会删除类并将其添加到特定的(this)元素
Another option would be:
This way you don't remove and add the class to the specific (this) element