如何在通过 load() 加载内容后更改或附加到 URL

  • 本文关键字:URL load 加载 javascript html url
  • 更新时间 :
  • 英文 :


我正在看Codyhouse(文章|演示(完成的演示,该演示使用loadNewContent((从另一个HTML文件中引入内容。一切都运行良好,但是,URL 保持不变,始终为/index.html。

我一直在调整 JS 以尝试使页面 URL 与内容一起更新,但这样做没有成功。我试过使用 replace((,但一直陷入循环......或删除一些代码片段,它根本不起作用。

关于我应该走哪条路线来完成这项工作的任何想法?我希望它按原样运行,但是如果您单击"关于",我希望页面URL为/about.html等。

function loadNewContent(newSection) {
//create a new section element and insert it into the DOM
var section = $('<section class="cd-section '+newSection+'"></section>').appendTo($('main'));
//load the new content from the proper html file
section.load(newSection+'.html .cd-section > *', function(event){
//add the .cd-selected to the new section element -> it will cover the old one
section.addClass('cd-selected').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
//close navigation
toggleNav(false);
});
section.prev('.cd-selected').removeClass('cd-selected');
});
$('main').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
//once the navigation is closed, remove the old section from the DOM
section.prev('.cd-section').remove();
});
if( $('.no-csstransitions').length > 0 ) {
//detect if browser supports transitions
toggleNav(false);
section.prev('.cd-section').remove();
}

我熟悉JS,但不是开发人员...所以任何帮助都非常感谢!!

你可以使用Javascript的history.pushState()方法做到这一点。 它与较旧的浏览器(

我建议在//close navigation评论之前添加 URL 操作,如下所示:

function loadNewContent(newSection) {
//create a new section element and insert it into the DOM
var section = $('<section class="cd-section '+newSection+'"></section>').appendTo($('main'));
//load the new content from the proper html file
section.load(newSection+'.html .cd-section > *', function(event){
//add the .cd-selected to the new section element -> it will cover the old one
section.addClass('cd-selected').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
// Update browser URL
history.pushState(null, newSection, newSection+'.html');
//close navigation
toggleNav(false);
});
section.prev('.cd-selected').removeClass('cd-selected');
});
$('main').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
//once the navigation is closed, remove the old section from the DOM
section.prev('.cd-section').remove();
});
if( $('.no-csstransitions').length > 0 ) {
//detect if browser supports transitions
toggleNav(false);
section.prev('.cd-section').remove();
}

重要提示:您的用户可能会复制/粘贴网址(与朋友共享.etc(,记住它们,甚至使用浏览器中的后退/前进功能。您应该在代码中进行设置以查看当前 URL,并提取相应的内容。这只能解决问题的一半(另一半超出了您的问题范围(。

延伸阅读:在不刷新页面的情况下更改 URL

更改网站上页面的典型方法是请求特定路由并从服务器获取内容,这意味着您请求路由"/index"并获取主页,然后当您按下"关于"按钮时,您请求来自路由"/about"的另一个页面,其中包含请求的页面内容。 您正在使用 JavaScript 在客户端加载内容,而不是向服务器发出请求。 如果您还想更改保留js函数的URL,我建议您操纵浏览器的历史记录:

https://developer.mozilla.org/en-US/docs/Web/API/History_API

通过这种方式,您既可以加载内容,也可以更改浏览器历史记录,更改URL,还可以添加"返回"到上一页的可能性。 也看看这个答案:

修改网址而不重新加载页面

最新更新