有没有办法在不刷新页面的情况下重新执行JS?
假设我有一个父页面和一个内页。当内页被调用时,它通过ajax被调用,替换父页面的内容。当用户点击返回时,我想将他们导航回父页面而无需重新加载页面。但是,父页面 UI 依赖于 javascript,所以在他们点击返回后,我想重新执行父页面的 javascript。这可能吗?
编辑:这是一些代码。我将我的代码包装在一个函数中,但是您将在何处以及如何调用该函数?
function executeGlobJs() {
alert("js reload success");
}
最佳答案
您可以使用 html5 history-api:
在您的 click
处理程序中,您将调用 pushState
方法,stat 存储当前状态以供以后重用:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...稍后如果用户返回浏览:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
这是一个非常简单的示例,当然并不完美! 您应该在这里阅读更多相关信息:
- https://css-tricks.com/using-the-html5-history-api/
- https://developer.mozilla.org/en-US/docs/Web/API/History_API
对于 ajax 和 DOM 相关的部分,您应该需要了解一些 jQuery http://api.jquery.com/jquery.ajax/ . (都是关于神奇的美元符号)
另一种选择是 hashchange
事件,如果您必须支持旧浏览器...
关于javascript - 在不重新加载整个页面的情况下重新执行js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356640/