(比之前谷歌更好的關鍵字)搜索一些,我發現我所需要的答案後,我寫了下面的功能:
function get_url_hash(argument) {
var hash = location.hash.replace('#','');
if(argument=='' || argument==undefined) {
return hash;
alert(blank);
} else {
var foundhash = false;
// specific argument given - let's find the value attached.
var hashblock = hash.split(',');
for(x in hashblock) {
var hasharray = hashblock[x].split('-');
if(hasharray[0]==argument) {
return hasharray[1];
foundhash = true;
}
}
if(foundhash==false) {
return false;
}
}
}
function modify_url_hash(argument, value) {
// This function goes through the entire hash,
// figures out which parts of the hash should be added, updated or removed based on entry,
// and then spits out final result.
var hash = get_url_hash();
var foundhash = false; // foundhash is set to false by default. if this hash is NOT found, then we add it at the end!
var hashcount = 0; // keep count of total # so as to determine where to put the commas etc.
var newhash = '';
if(hash.length>0) {
var hashblock = hash.split(',');
for(x in hashblock) {
var hasharray = hashblock[x].split('-');
if(hasharray[0]==argument) {
hasharray[1] = value;
foundhash = true;
}
if(hasharray[1]!=false && hasharray[1]!='') { // if new value is NOT false, we keep it in.. otherwise don't feed it to newhas so it disappears.
if(hashcount>0) { newhash = newhash+','; }
newhash = newhash+hasharray[0]+'-'+hasharray[1];
hashcount++;
}
}
}
if(foundhash==false) {
// this is a new hash block.
if(hashcount>0) { newhash = newhash+','; }
newhash = newhash+argument+'-'+value;
}
location.hash = newhash;
}
這看起來很複雜,看似簡單的任務。請讓您的原始問題更具體,我確信社區可以找到更優雅的東西。 –
它完美地工作,並做我需要的一切 - 24小時後,更多的測試,它的工作神奇。訪問http://traumatech.sonikastudios.com/ourproducts並測試產品上的下拉菜單和頁碼。基本上,每次調用散列值時,我都會運行modify_url_hash('category',12);或類似的東西。如果沒有類別,則將類別12添加到#哈希值。如果有,它將數字更改爲新值。如果我運行modify_url_hash('category',false);那麼它只是將其刪除。 – jeffkee