单击时将Class 添加到图像。如果单击另一个图像,请删除该类并将其添加到新图像中
我有一个包含四个图像的列表。每个图像在任何给定时间都应该只有一个活动类。 (类似于单选按钮)。
到目前为止,我的代码支持这一点: http://jsfiddle.net/tctc91/HyHgp/
var themeChooser = $('.themeChooser ul li img');
themeChooser.click(function() {
if(!themeChooser.hasClass('themeSelected')) {
$(this).addClass('themeSelected');
} else {
$(this).removeClass('themeSelected');
}
});
我的问题是,当 .themeSelected 类是已经处于活动状态,如果您单击其他图像,它将不起作用。我需要它,所以如果它已经处于活动状态并且您单击不同的图像,它会删除现有的类并将其添加到新图像中。
谢谢!
I have a list containing four images. Each image should only have one active class at any given time. (similar to radio buttons).
My code so far supports this fine:
http://jsfiddle.net/tctc91/HyHgp/
var themeChooser = $('.themeChooser ul li img');
themeChooser.click(function() {
if(!themeChooser.hasClass('themeSelected')) {
$(this).addClass('themeSelected');
} else {
$(this).removeClass('themeSelected');
}
});
My problem is that when the .themeSelected class is already active, It will not work if you click on a different image. I need it so IF it is already active and you click on a different image, it removes the existing class and adds it to the new image.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在点击处理程序中简单添加
$('.themeSelected').removeClass('themeSelected');
即可实现您想要的效果。实例: http://jsfiddle.net/sT9jE/
编辑:不完全是如此简单,上面的代码停止了对所选元素的重新单击取消选择。因此,您实际上需要添加此内容:
请参阅此实时示例: http://jsfiddle.net/HM5DF/
The simple addition of
$('.themeSelected').removeClass('themeSelected');
inside your click handler achieves what you want.Live example: http://jsfiddle.net/sT9jE/
Edit: Not quite so simple, the above stops a re-click on the selected element unselecting. Therefore you actually need this addition:
See this Live example: http://jsfiddle.net/HM5DF/