如何使用#创建动态页面

How to create dynamic pages using # ?

本文关键字:动态 创建 何使用      更新时间:2023-09-26

我注意到像Twitter和其他一些网站这样的很多页面都在设计中加入了AJAX。引起我注意的一件事是#!在url。我想知道我如何能为自己或他们正在使用的方法做到这一点,谢谢!

你可以从一些非常简单的东西开始,使用Hashchange或BBQ插件。阅读这两种产品的说明书,你就会明白了。

这里是一个简短而一般的介绍:http://code.google.com/intl/en-EN/web/ajaxcrawling/docs/html-snapshot.html

更新:

好,让我们以Hashchange插件为例。下面的代码非常原始,但我认为它将有助于理解

的基本部分HTML:

<ul>
    <li><a href="/about">About</a></li>
    <li><a href="/contact">Contact Us</a></li>
    <li><a href="/links">Links</a></li>
</ul>
<div id="page"></div>

JS:

$(function(){
    /*
     * We override the default
     * behaviour of our links
     * and change the hash of the URL,
     * e.g. '/contact' -> '#contact',
     * so the address bar of the browser
     * would change to 
     * 'http://example.com#contact'
     */
    $('ul').find('a').click(function() {
        var hash = $(this).attr('href').replace('#', '');
        window.location.hash = hash;
        return false;
    });
    /*
     * The main hashchange logic
     *
     * We use jQuery.load to retrieve
     * a specific part of the loaded document,
     * #page here
     */
    $(window).hashchange(function() {
        var newLoc = window.location.hash.replace('#', '');
        $('#page').load('/' + newLoc + ' #page');
    });
    $(window).hashchange();
});