【问题标题】:changing the url without loading a new page在不加载新页面的情况下更改 url
【发布时间】:2016-10-28 22:21:00
【问题描述】:

对于我的单页网站,我有一个项目索引。如果单击一个项目,它会在同一页面上打开幻灯片。所以基本上,我只有一个 URL,如果有人想链接到特定项目,他们不能。

我正在尝试这样做,以便如果我单击一个项目,它会更改 URL。因此,该 URL 可用于在打开该项目的情况下访问我的网站。

Here 是我目前所拥有的链接。

作为参考,我正在尝试实现在此 site 上找到的东西。

我找到了一些很好的建议here,但是当我使用这样的东西(如下)时会发生什么,会创建一个新的 URL,但如果我将该 URL 租用到浏览器中,它不会打开项目。

<a href="#" id='click'>Click to change url to bar.html</a>

<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
   history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>

【问题讨论】:

    标签: javascript jquery html css url


    【解决方案1】:

    在这种情况下使用哈希可能效果最好

    $(document).ready(function({
    
        //loading a page
        var project = window.location.hash 
        yourProjectLoadFunction(project);        
    
        //setting a url
        $('.number').click(function(e){ 
            $this = $(this);
            window.location.hash = $this.attr('id');
        });
    });
    

    【讨论】:

      【解决方案2】:

      您可以在具有幻灯片作为唯一 URL 的元素处使用 id;在.ready() 开始动画元素,其中id 匹配.location.hash

      $().ready(function() {
        // `location.hash`: `id`: `#slideshow1` of element linked to
        // from, e.g., `http://example.com/#slideshow1`
        var currentSlideshow = $(location.hash);
        // do slideshow stuff at `currentSlideshow`: `#slideshow1` element
      })
      

      【讨论】:

        【解决方案3】:
        function processAjaxData(response, urlPath){
             document.getElementById("content").innerHTML = response.html;
             document.title = response.pageTitle;
             window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
         }
        

        您可以使用`window.onpopstate 来感知后退/前进按钮导航

        window.onpopstate = function(e){
            if(e.state){
                document.getElementById("content").innerHTML = e.state.html;
                document.title = e.state.pageTitle;
            }
        };
        

        我希望有更多技能的人帮我检查一下

        【讨论】:

        • 你能帮我实现这个吗?我只是尝试将其添加到我的 js 代码中,但它没有做任何事情
        猜你喜欢
        • 2020-10-04
        • 1970-01-01
        • 2013-07-07
        • 1970-01-01
        • 2020-04-20
        • 2013-06-21
        • 2020-12-29
        • 2011-11-27
        相关资源
        最近更新 更多