以下switch语句未捕获不存在的cookie。
switch (stateCookie) {
case 'Virginia':
window.location = '/Teacher-Login/VA';
break;
case 'North Carolina':
window.location = '/Teacher-Login/NC';
break;
case 'South Carolina':
window.location = '/Teacher-Login/SC';
break;
case null:
window.location = '/Teacher-Login/VA';
break;
case '':
window.location = '/Teacher-Login/VA';
default:
window.location = '/pages/state-login/login.html';
好的,我已经尝试了几件事,但我仍然莫名其妙地遇到了麻烦。这是我现在的代码:
$('#welcome select').change(function () {
var stateSelected = $('option:selected', this).val();
var stateCookie = getCookie("ia_state");
if(stateSelected != stateCookie)
{
setCookie('ia_state', stateSelected);
switch (stateCookie) {
case 'Virginia':
case null:
case '':
window.location = '/Teacher-Login/VA';
break;
case 'North Carolina':
window.location = '/Teacher-Login/NC';
break;
case 'South Carolina':
window.location = '/Teacher-Login/SC';
break;
default:
window.location = '/pages/state-login/login.html';
}
}
});
正在评估switch语句,但它始终是默认情况。如果cookie为null / undefined,我还没弄清楚如何捕获它。
答案 0 :(得分:3)
你错过了一个休息时间:
...
case '':
window.location = '/Teacher-Login/VA';
break;
default:
window.location = '/pages/state-login/login.html';
break;
mdn有项目功能:
function hasItem(sKey) {
return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
答案 1 :(得分:1)
我同意Mike Stewart的观点。你错过了一个休息时间,所以如果它以''的形式返回,那么它将继续使用默认语句。如果你在改变之后仍然得到奇怪的结果,那么问题可能就在其他地方。
var loc = '';
switch (stateCookie) {
case 'Virginia':
case null:
case '':
case undefined:
loc = '/Teacher-Login/VA';
break;
case 'North Carolina':
loc = '/Teacher-Login/NC';
break;
case 'South Carolina':
loc = '/Teacher-Login/SC';
break;
default:
loc = '/pages/state-login/login.html';
break;
};
window.location = loc;
编辑:添加了未定义的案例
答案 2 :(得分:0)
类似的东西:
if( $.cookie('cookiename') == null ) { /// is null }
答案 3 :(得分:0)
在进入交换机之前验证您的Cookie,例如:
stateCookie = (typeof stateCookie != 'string')?'':stateCookie;
然后转换。
因此,请从开关中删除case null。
case '':
window.location = '/Teacher-Login/VA';