【发布时间】: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