【问题标题】:DOMContentLoaded event not working in SPA route changeDOMContentLoaded 事件在 SPA 路由更改中不起作用
【发布时间】:2022-01-09 19:53:57
【问题描述】:

我有一个 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 using history api and ES6 classes

【问题讨论】:

    标签: javascript dom addeventlistener event-listener


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢。我在一些路线中使用了这个 popstate 事件,但在这里忘记了。
    猜你喜欢
    • 2017-02-20
    • 2021-01-11
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2017-02-24
    • 2022-01-25
    相关资源
    最近更新 更多