开发者

if window.location.href has 'sometext' inside - do this

Currently working on something which uses ajax for some pagination. What I'm looking to do is add something like referal=3 to the end of some links then when they go to that link I'll insert a back button with the window location for example:

User uses the ajax pagination, goes to page 3 I'll add ?ref=3 to the end of the link or something so it would like this this:

http://foo.com/somepage/?ref=3

(not sure if that's a corrent way of doing it)

Then 开发者_如何转开发the user clicks that link and I'll append a back button on that page with that link.

So when they go back to the homepage using the generated button the window.location.href will be:

http://foo.com?ref=3

The idea is that when they click that back button, the ajax pagination will load to page 3.

I'm not sure how else to explain this, but does anyone know how I would go about doing a conditional statement dependant on the window.location.href?


To find a if the url contains some string:

if (document.location.href.search("ref=3")!=-1){
 alert('got ref=3'); 
}


You can use this function to get parts of the query string:

function getQueryString(variable){
    // Grab the query string part of the URL (everything after the ?)
    var query = window.location.search.substring(1);

    // If you don't specify which value you want, return the whole thing
    if(!variable) return query;

    // Split the query string to key=value pairs into an array
    var vars = query.split('&');

    // Loop through them to find the one we're looking for
    for (var i = 0; i < vars.length; i++){
        // Split key and value
        var pair = vars[i].split('=');

        // If the key matches our parameter, return the value
        if (pair[0] == variable){
            return pair[1];
        }
    }
    // If not found, return empty string
    return '';
}

Then you can get the value as a string by:

var value = getQueryString('ref');

// Conditional code if it is a certain value, do something
if(value === '3'){
    // Do something
}

You can also get it as a number by using parseInt():

var value = parseInt(getQueryString('ref'), 10);

if(value === 3){
    // Do something
}


I'm not sure I fully understand what you want to do, but it sounds like you want to look into using the location.hash property.

Using a jQuery plugin, such as hashchange, you can add ajax calls to the browsers history. Also, all pages will be bookmarkable. It's a pretty broad subject, but the link I provided should get you started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜