簡単なケース:
var vh = "layout1";
$('#foo-bar').addClass(function () {
$(this).prop('class', '');
return vh == 'layout1' ? 'horizontal' : 'vertical';
});
編集が追加されました:決定的な単純なケースは、一致するものがない場合、クラスに設定しません
var vh = "layout9";
$('#foo-bar').prop('class',function () {
return vh == 'layout1' ? 'horizontal' : (vh == "layout2" ? 'vertical' : (vh=="layout3" ? "reddy" : ""));
});
より複雑なケース:
var vh1 = "layout2";
var classList = $('#foo-bar').prop('class').split(/\s+/);
$('#foo-bar').addClass(function (vh1) {
var self = this;
$.each(classList, function (index, item) {
//IF you want to keep one, check it here
if (item != "keepme") {
$(self).removeClass(item);
}
});
switch (vh1) {
case "layout1":
return "horizontal";
case "layout2":
return "vertical";
default:
return "reddy";
}
});
EDIT2: 一致するものがない場合は、クラスをそのままにしておきます! (注意、すべてのクラスを新しいセットに置き換えます)
<div id="foo-bar" class='reddy3 freddy' >hi</div>
存在し続ける:
var vh = "nomatches";
$('#toggle').prop('class',function (i,v) {
return vh == 'layoutA' ? 'horizontal' : (vh == "layout2" ? 'vertical' : (vh=="layout3"? "reddy":v));
});// keeps "reddy3 freddy"
複数設定:
var vh = "greenhorizontal";
$('#toggle').prop('class',function (i,v) {
return vh == 'layout2' ? 'horizontal' : (vh == "layout2" ? 'vertical' : (vh=="greenhorizontal"? "greeny horizontal":v));
});//sets both "greeny" and "horizontal", wipes out existing
参考までに、vh を「myvar」に、完全なソリューションを vh1 に置き換えてください