简单的例子:
var vh = "layout1";
$('#foo-bar').addClass(function() {
$(this).prop('class', '');
return vh == 'layout1' ? 'horizontal' : 'vertical';
});
编辑新增:definative简单的情况下,将其设置为无类,如果没有匹配
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";
}
});
编辑2:如果没有匹配,就让这些类独自一人!(注意,替换所有类新集)
<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
仅供参考,substitue你的 “MYVAR” 为VH和VH1全解决方案
哪里是 “MYVAR” 是从哪里来的?一个输入? – Adunahay
这来自我的WordPress的选项设置,不要担心它。我实现了它,并成功将我的选项值存储在myvar中,并通过alert(myvar)进行检查; – galexy
这是两个问题,因此我提交的两个答案 –