我试图使它成为,当我单击一个div时,所有其他div都变成了“取消选择的”(也就是说,只有选择的div的background-image不同,其他的background-image被重置为原始的),这样只选择/激活了单击。每个div都有一个单独的on/off映像。
http://jsfiddle.net/sergep/5QsCy/
代码有很多重复。我真的不知道如何处理‘取消选择’所有其他div(除了活动的div)的想法,而不必使用更多的冗余代码。
是否有需要整理(即泛化和删除冗余)我的jsFiddle:
$(".gameboy").click(function () {
var img1 = "url(\"https://cdn3.iconfinder.com/data/icons/funky/136/Game-1-128.png\")";
var img2 = "url(\"https://cdn3.iconfinder.com/data/icons/funky/136/Game-2-128.png\")";
if ($(this).css("background-image") == img1) {
$(this).css("background-image", img2);
}
else {
$(this).css("background-image", img1);
}
});
$(".switch").click(function () {
var img1 = "url(\"https://cdn3.iconfinder.com/data/icons/mobiactions/512/turn_off_on_power-128.png\")";
var img2 = "url(\"http://icdn.pro/images/en/o/n/on-off-icone-4799-128.png\")";
if ($(this).css("background-image") == img1) {
$(this).css("background-image", img2);
}
else {
$(this).css("background-image", img1);
}
});
$(".face").click(function () {
var img1 = "url(\"https://cdn3.iconfinder.com/data/icons/glyph/227/Smile-128.png\")";
var img2 = "url(\"https://cdn3.iconfinder.com/data/icons/glyph/227/Pacman-1-128.png\")";
if ($(this).css("background-image") == img1) {
$(this).css("background-image", img2);
}
else {
$(this).css("background-image", img1);
}
});发布于 2013-10-21 12:26:16
既然您正在更改的只是样式,那么为什么不创建一个类'active‘并将其应用于刚刚单击的div,同时将该类从其同级div中删除。所有这些都可以归结为一个简单的单击函数:
$('div').click(function(){
$(this).siblings('div').removeClass('active');
$(this).addClass('active');
});然后,只需为每个div的.active类设置css样式:
.gameboy.active {...}
.switch.active {...}
.face.active {...}顺便说一句,单击函数中的“div”选择器仅用于示例。很可能您不希望站点上的每个div都是可点击的,因此我要么给所有这3个div都提供一个类,要么使用一个更具体的css选择器来指定它们。
https://stackoverflow.com/questions/19494190
复制相似问题