我有一个功能可以改变我网站上12个DIV之一的文本颜色。
$('.position_select').change(function(){
var selected = $(this).val();
var shelf = $("#mockup_shelf_" + selected)
$(shelf).css({ color: "#FF6633" });
}).change();
它是一个模型,供用户显示他们选择显示按钮的位置。它基于在select标签中选择了哪个数字(从1到12):
f.select :position, (1..12), {prompt: 'Select Position'}, {required: 'true', class: "position_select" }
如果用户取消选择此特定位置并选择另一个,我想将此DIV的文本更改回黑色(或所有未选择的DIV)。我该怎么做? 颜色可以回到页面重新加载时应该是什么,但这不是重点。
答案 0 :(得分:1)
最简单的方法是将所有元素更新为默认颜色,然后更改与所选项目对应的元素的颜色,如下所示:
$('.position_select').change(function(){
//reset all elements color
$("[id^=mockup_shelf_]").css({ color: "#000000" });
//now find and set the color of the selected item
var selected = $(this).val();
var shelf = $("#mockup_shelf_" + selected)
$(shelf).css({ color: "#FF6633" });
}).change();
我使用starts with
属性选择器,因为每个ID的开头都是相同的。
http://www.w3schools.com/cssref/sel_attr_begin.asp
[attribute ^ = value]选择器匹配其属性的每个元素 值以指定值开头。
或者,您可以为所有mockup_shelf
元素分配相同的类,然后使用此类选择器将它们全部定位:$(".mockup_shelf").css({ color: "#000000" });
由于好东西三分,你还可以完全消除脚本中的任何样式信息,并在样式表中创建2个css类(允许您更轻松地进行更复杂的样式)。例如:
.mockup_shelf {
color: #000000;
}
.mockup_shelf.selected {
color: #FF6633;
}
您的所有mockup_shelf
元素都有mockup_shelf
类,然后在脚本中您可以像这样添加或删除selected
类:
$('.position_select').change(function(){
//reset selected element's color
$(".mockup_shelf.selected").removeClass("selected");
//now find and set the color of the selected item
var selected = $(this).val();
var shelf = $("#mockup_shelf_" + selected)
$(shelf).addClass("selected");
}).change();
修改强> 既然你澄清了你有一个多选框,我已经开始了,并创建了一个样本小提示,展示了如何通过多个选择完成此操作: https://jsfiddle.net/ofhw085r/
$('.position_select').change(function() {
//remove class from all shelves to reset them
$(".mockup_shelf.selected").removeClass("selected");
var $position_select = $(this); //explicitly labeling this to avoid confusion in the next part
$position_select.find("option:selected").each(function() {
var $option = $(this); //'this' now has a new context, so label it to avoid confusing it with 'this' in the outer context
var shelf = $("#mockup_shelf_" + $option.val());
shelf.addClass("selected");
});
}).change();
基本上,每次更改事件在select
上触发时,您都会重置所有mockup_shelf
元素上的样式,然后遍历每个selected
选项(使用jquery&# 39;内置:selected
选择器),然后将selected
类添加到关联的架子。