在页面加载时,我正在检查URL地址栏中是否有字符串,如果是,则应该在URL中更改带有该字符串的菜单项文本。但如果没有字符串,那么它应该写一个不同的文本。
var hash = document.location.hash;
// create an object to act like a dictionary to store each value indexed by its key
var partDic = {};
// remove the leading "#" and split into parts
var parts = hash.substring(1).split('&');
// If you just want the first value, whatever it is, use this.
// But be aware it's a URL so can be set to anything in any order, so this makes little sense
// var string = parts[0].split('=')[1];
// build the dictionary from each part
$.each(parts, function(i, v) {
// do the "=" split now
var arr = v.split("=");
// decode to turn "%5B" back into "[" etc
var key = decodeURIComponent(arr[0]);
var value = decodeURIComponent(arr[1]);
// store in our "dictionary" object
partDic[key] = value;
});
var timeoutId = setInterval(function() {
if ("comboFilters[Agencies]" in partDic) {
var ag = partDic["comboFilters[Agencies]"].substring(1);
$('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
} else {
$('.Agency .dropdown-toggle').html("All agencies").append(' <span class="caret"></span>');
}
if ("comboFilters[Clients]" in partDic) {
var cl = partDic["comboFilters[Clients]"].substring(1);
$('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
} else {
$('.Client .dropdown-toggle').html("All clients").append(' <span class="caret"></span>');
}
if ("comboFilters[Years]" in partDic) {
var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
$('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
} else {
$('.Year .dropdown-toggle').html("All years").append(' <span class="caret"></span>');
}
clearInterval(timeoutId);
}, 1000);
正在发生的事情是,如果没有字符串,则菜单项不会正确地拾取else
文本。
网址为:
http://www.example.com/xchanges/#comboFilters%5BAgencies%5D=&comboFilters%5BYears%5D=.y2012
使用该URL,代理商的菜单项应该选择All agencies
,因为它是空的,但它没有这样做。它什么都没打印
答案 0 :(得分:0)
只要comboFilters [Agencies]在url参数中,您的代码就会在partDic
中创建一个名为comboFilters [Agencies]的键,但它是否有值。
您需要检查值
//if it exists and has a non empty value
if(partDic['comboFilters[Agencies]'] && partDic['comboFilters[Agencies]'] != ""){
} else {
}
答案 1 :(得分:0)
问题是代理商值为空,但仍在添加到您的partDic
列表中
这将检查是否有值
$.each(parts, function(i, v) {
// do the "=" split now
var arr = v.split("=");
// decode to turn "%5B" back into "[" etc
var key = decodeURIComponent(arr[0]);
var value = decodeURIComponent(arr[1]);
if( value ) {
// store in our "dictionary" object
partDic[key] = value;
}
});