开发者

Add history to jQuery ajax

I can't figure out how to add the history plugin functionality to my (really simple) ajax code.

Here's my code so far:

$(function() {

    $.ajaxSetup({ cache: true });
    var hijax = $('ul.hijax a');
    var loader = $('<div id="spinner"></div>');
    hijax.click(function(e){
      hijax.removeClass('ajax-on');
        $(this).addClass('ajax-on');
        var url = $(this).attr('href') + ' #biog-container';
        $("#ajax-container").html(loader).load(url);
        e.preventDefault();
    });
});

This pulls the contents of the the linked page containing a div with an id of 'biog-containers' (The is开发者_C百科 a list of names with links to peoples' biographies - it's a site for a baroque orchestra!).

The ajax calls works great (yay jQuery!), but I've googled and googled about adding support for the history plugin and (stupid front-end guy that I am) I just can't figure it out.

Thanks for the help.


You can create a global array, holding the items clicked though the script. Push the elements at each click, but have present the last item WON'T be return item.

At a return point, check if your array has more than one item, pull one item and discard it (that item represents the current page), pull another item and trigger a click over it.

This code is not tested!:

$(function() {
    var links = new Array(),
    hijax = $('ul.hijax a'),
    loader = $('<div id="spinner"></div>'),
    container = $('#ajax-container'),
    content = container.html();

    $.ajaxSetup({ cache: true });

    hijax.click(function(e){
        var $this = $(this),
        url = $this.attr('href') + ' #biog-container';

        e.preventDefault();
        links.push($this);

        hijax.removeClass('ajax-on');
        $this.addClass('ajax-on');
        container.html(loader).load(url);
    });

    $('#back-button').click(function(e){
        var link;
        e.preventDefault();

        if (links.length > 1) {
            // This represents the current link
            links.pop();
            // This represents the past link
            link = links.pop();
            link.click();
        }
        else {
            // This may be empty, or represent the current content
            links.pop();
            // Show the original content
            container.html(content);
        }
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜