我有一個 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 中獲取帖子后運行此函式。
這是我使用的 repo(結構相同)使用歷史 API 和 ES6 類的 SPA
uj5u.com熱心網友回復:
如果您有 SPA 應用程式,這意味著DOMContentLoaded事件將在應用程式準備就緒時(而不是在您在路線上導航時)觸發一次。
根據您的邏輯,應該在位置歷史記錄更改時觸發此代碼。您可以嘗試將DOMContentLoaded事件偵聽器更改為popstate:
window.addEventListener('popstate', function (event) {
// The URL changed...
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375209.html
標籤:javascript dom 添加事件监听器 事件监听器
上一篇:為什么我的document.querySelector回傳null?
下一篇:無法加載計算器按鈕
