2011-12-02 66 views
1

雖然通過AJAX等檢索項目,這些鏈接設置爲做到這一點:使用jQuery追加URL與錨#

$(this).click(function(){ 
ajax_function(); // hypothetical ajax call that puts data into a <div> of my choice 
return false; 
}); 

在這種情況下,我想知道最好的辦法是利用jQuery的是什麼添加東西到我的URL格式爲:

http://www.mydomain.com/products

變成

http://www.mydamain.com/products#category-12,page-4

進一步注意 - 我正在談論瀏覽器的實際URL(在URL欄中),而不是作爲DOM一部分的URL。

回答

1

(比之前谷歌更好的關鍵字)搜索一些,我發現我所需要的答案後,我寫了下面的功能:

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; 
} 
+0

這看起來很複雜,看似簡單的任務。請讓您的原始問題更具體,我確信社區可以找到更優雅的東西。 –

+0

它完美地工作,並做我需要的一切 - 24小時後,更多的測試,它的工作神奇。訪問http://traumatech.sonikastudios.com/ourproducts並測試產品上的下拉菜單和頁碼。基本上,每次調用散列值時,我都會運行modify_url_hash('category',12);或類似的東西。如果沒有類別,則將類別12添加到#哈希值。如果有,它將數字更改爲新值。如果我運行modify_url_hash('category',false);那麼它只是將其刪除。 – jeffkee

1

可能類似於

oldlink = $('#mylinkselector').attr("href"); 
newlink = oldlink="#category-12,page-4"; 
$("#mylinkselector").prop("href",newlink); 
+0

萬一你不知道'prop'功能go [here](http://api.jquery.com/prop/) – Starx

+0

我在談論瀏覽器窗口的實際URL。我希望能夠允許啓動正確的AJAX調用的URL共享根據URL條目獲取正確的類別和頁面號。 – jeffkee