DOMContentLoaded事件在SPA路由更改中不起作用



我有一个SPA代码,其中我使用历史api和ES6类将html内容动态地插入到DOM中。

我在执行脚本之前使用了事件侦听器,如DOMContentLoaded和位置路径检查,但内容仍然未定义。

//probably be fetching from a source
document.addEventListener("DOMContentLoaded",() => {
// function truncateText(text,length) {
//  if (text.length > length) {
//      const truncatedText = text.substr(0,length);
//      return truncatedText + "..."
//  }
//  return text;
// }
if (window.location.pathname == "/dashboard/posts") {
const posts = document.querySelectorAll('.post'); //undefined but still exists
console.log(posts.length == 0 ? false : true)
posts.forEach((post) => {
console.log("ran")
const postTextH = post.children[0].children[1].children[0]
const postText = post.children[0].children[1].children[1]
console.log(postText,postTextH + "here")
postText.innerText = truncateText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco",150)
postTextH.innerText = truncateText("How to never give up!",70)
})
}
})

所以我的问题是,在页面中的内容被正确加载并从dom获得帖子后,我如何运行这个函数。

这是我正在使用的回购(结构相同(SPA使用历史api和ES6类

如果您有SPA应用程序,这意味着当应用程序准备就绪时(而不是在路线上导航时(,DOMContentLoaded事件将被触发一次。

根据您的逻辑,当位置历史记录发生更改时,应该触发此代码。您可以尝试将DOMContentLoaded事件侦听器更改为popstate:

window.addEventListener('popstate', function (event) {
// The URL changed...
});

最新更新