使用jQuery通过锚点附加URL#

时间:2011-12-02 06:12:31

标签: jquery url anchor

通过AJAX等检索项目时,链接设置为:

$(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。

2 个答案:

答案 0 :(得分:1)

可能类似

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

答案 1 :(得分:1)

在搜索了更多内容后(在Google上使用了比以前更好的关键字),我找到了我需要的答案,并编写了以下功能:

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