简体   繁体   English

使用jQuery.load时如何获取和更改URL

[英]How to get and change url when using jQuery.load

I want to change the url according to the menu pages, so to easily share a link to someone else, since each page has its own url name. 我想根据菜单页面更改URL,以便轻松共享与他人的链接,因为每个页面都有自己的URL名称。

So, I have a function that loads the file content. 因此,我有一个加载文件内容的功能。 But how to implement it with the url change also into the function? 但是如何将url更改也实现到函数中呢?

<script>
    function getfile(data) {
        var file= data+'.html';
        $('#content').load(file);
    }
</script>

Here is the navigation using onclick function. 这是使用onclick功能的导航。

<ul>
    <li><a href="#" onclick="getfile('profile')">Profile</a> </li>
    <li><a href="#" onclick="getfile('about')">About</a> </li>
    <li><a href="#" onclick="getfile('contact')">Contact</a> </li>    
</ul>


<div id="content"></div>

You could use the History API . 您可以使用History API The pushState method will allow you to change the current page's URL, without reloading the content. pushState方法将允许您更改当前页面的URL,而无需重新加载内容。

Example: 例:

<script>
    function getfile(data) {
        var file= data+'.html';
        $('#content').load(file);
        history.pushState(null, null, file);
    }
</script>

You may also be interested in the popstate event , to detect when the browser travels back to the previous pages. 您可能还对popstate事件感兴趣,以检测浏览器何时返回上一页。

Update: 更新:

In order to load files for a sub directory, you will need to know the path to the root directory for the site. 为了加载子目录的文件,您将需要知道站点根目录的路径。 Something like the following will work if the site is at the root directory. 如果站点位于根目录下,则类似以下的内容将起作用。

<script>
    var rootPath = '/';
    function getfile(data) {
        var file= rootPath+data+'.html';
        $('#content').load(file);
        history.pushState(null, null, file);
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM