javascript - 在不重新加载整个页面的情况下重新执行js

标签 javascript jquery html ajax

有没有办法在不刷新页面的情况下重新执行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()
})

这是一个非常简单的示例,当然并不完美! 您应该在这里阅读更多相关信息:

对于 ajax 和 DOM 相关的部分,您应该需要了解一些 jQuery http://api.jquery.com/jquery.ajax/ . (都是关于神奇的美元符号)

另一种选择是 hashchange 事件,如果您必须支持旧浏览器...

关于javascript - 在不重新加载整个页面的情况下重新执行js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356640/

相关文章:

php - 使用 Php/JavaScript/Html/CSS 创建可打印内容

javascript - 使用 jQuery 删除附加元素

javascript - 使用 Python 进行 AJAX 调用

javascript - 将分页排成一行有问题吗?

javascript - 使用下划线修改另一个对象内部的对象内部的数组?

javascript - 替换不是特定标签子字符串的子字符串

javascript - 如何清除可动态数据并添加新数据?

javascript - Jquery 执行点击 <img>

javascript - 当具有 CSS 属性的变量发生变化时如何执行 jquery

javascript - React.js 从系统加载 Markdown 文件作为字符串