简单案例:
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
仅供参考,用你的“myvar”代替 vh 和 vh1 以获得完整的解决方案