最も簡単な方法は、単にデフォルトの色にすべての要素を更新し、このように選択した項目に対応する要素の色を変更することです:
$('.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
[属性^ =値]セレクタは、その属性 値が指定された値で始まるすべての要素に一致します。
代わりに、あなたはすべての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();
EDIT あなたは明らかにしているので複数の選択肢でこれを達成する方法を示すサンプルフィドルを作成しました。
$('.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
の変更イベントが発生するたび、あなたは(jQueryのビルトイン:selected
セレクタを使用して)すべてのselected
オプションを介してすべてのmockup_shelf
要素と、ループ上のスタイルをリセットし、その後selected
を追加しますクラスを関連付けられたシェルフに割り当てます。
'$(" mockup_shelf_ "+ $(this)).val())を使ってハンドラの最後の3行を1つまたは2つに短縮するかもしれません。素晴らしい答えですが、最後にあなたが提案するアプローチが本当に好きです。 – IrkenInvader
答えをいただきありがとうございました。本当に素晴らしいです。このソリューションの問題点は、選択した1つの位置だけでなく、残りのDIVを色分けして黒で表示することです。 –
@JoeyEkwatrepedreyあなたは全く同じテクニックを使用することができます。選択したすべての位置に選択した色を設定するだけです。 – Joel