window.location.hash 返回带有数字符号的哈希值。
这可以使用 4 种方法中的一种来解决。我还删除了第一个if
不需要的。
方法 #1(最佳):从哈希属性中删除 #
$page = $('#content');
var hash = window.location.hash.substr(1);
if(hash == 'news') {
$xmlFile = 'xml/news.xml';
$("#content").createNewsEntry();
} else if (hash == 'biography'){
$xmlFile = 'xml/bio.xml';
$("#content").createBioEntry();
} else if (hash == 'awards'){
$xmlFile = 'xml/awards.xml';
$("#content").createBioEntry();
} else if (hash == 'discography'){
$xmlFile = 'xml/discography.xml';
$("#content").createBioEntry();
}else{
alert('this should fire off because there is no hash but it doesnt');
$xmlFile = 'xml/home.xml';
$("#content").createHomeEntry();
}
方法#2(最有效):使用开关和substr
哈希
$page = $('#content');
switch (window.location.hash.substr(1)) {
case 'news':
$xmlFile = 'xml/news.xml';
$("#content").createNewsEntry();
break;
case 'biography':
$xmlFile = 'xml/bio.xml';
$("#content").createBioEntry();
break;
case 'awards':
$xmlFile = 'xml/awards.xml';
$("#content").createBioEntry();
break;
case 'discography':
$xmlFile = 'xml/discography.xml';
$("#content").createBioEntry();
break;
default:
alert('this should fire off because there is no hash but it doesnt');
$xmlFile = 'xml/home.xml';
$("#content").createHomeEntry();
break;
}
方法#3(最简单):添加哈希
$page = $('#content');
if(window.location.hash == '#news') {
$xmlFile = 'xml/news.xml';
$("#content").createNewsEntry();
} else if (window.location.hash == '#biography'){
$xmlFile = 'xml/bio.xml';
$("#content").createBioEntry();
} else if (window.location.hash == '#awards'){
$xmlFile = 'xml/awards.xml';
$("#content").createBioEntry();
} else if (window.location.hash == '#discography'){
$xmlFile = 'xml/discography.xml';
$("#content").createBioEntry();
}else{
alert('this should fire off because there is no hash but it doesnt');
$xmlFile = 'xml/home.xml';
$("#content").createHomeEntry();
}
方法#4(最差):使用indexOf
$page = $('#content');
if(window.location.hash.indexOf('news') === 1) {
$xmlFile = 'xml/news.xml';
$("#content").createNewsEntry();
} else if (window.location.hash.indexOf('biography') === 1){
$xmlFile = 'xml/bio.xml';
$("#content").createBioEntry();
} else if (window.location.hash.indexOf('awards') === 1){
$xmlFile = 'xml/awards.xml';
$("#content").createBioEntry();
} else if (window.location.hash.indexOf('discography') === 1){
$xmlFile = 'xml/discography.xml';
$("#content").createBioEntry();
}else{
alert('this should fire off because there is no hash but it doesnt');
$xmlFile = 'xml/home.xml';
$("#content").createHomeEntry();
}