动态添加博客帖子遇TypeError:无法给字符串添加innerText属性
动态添加博客帖子的问题修复
问题分析
你的代码里有两个核心错误导致帖子无法正常显示,尤其是图片部分:
- 图片元素创建逻辑错误:
const authorImg = document.createElement('img').src = "";这行连续赋值后,authorImg存储的是空字符串,而不是你创建的<img>元素。后续对authorImg.innerText的操作完全无效,还会导致整个函数执行异常,连标题、作者这些内容都没法正常渲染。 - 图片内容设置方式错误:
<img>标签是通过src属性指定图片地址的,不能用innerText来设置——它本身就没有文本内容区域。
修正后的代码
// 创建DOM变量 let button = document.getElementById("btn"); let postForm = document.getElementById("post-form"); let displayPostsCont = document.querySelector(".displayPosts"); let title = document.getElementById("postTitle"); let author = document.getElementById("authorName"); let text = document.getElementById("textP"); let image = document.getElementById("newPostImageUrl"); // 新帖子添加后会被推入此数组 const posts = [{ title: "My first blog post", author: "Kam", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Pretium aenean pharetra magna ac placerat vestibulum lectus.", image: "https://images.pexels.com/photos/936048/pexels-photo-936048.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" }, { title: "My second blog post", author: "Kam", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Pretium aenean pharetra magna ac placerat vestibulum lectus.", image: "https://images.pexels.com/photos/936048/pexels-photo-936048.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" } ]; const addPost = (title, author, text, image) => { // 补充添加新帖子到数组并渲染的逻辑 posts.push({title, author, text, image}); createBlogPostElement({title, author, text, image}); } // 创建博客帖子元素并添加到DOM const createBlogPostElement = ({title, author, text, image}) => { // 创建元素 const postDiv = document.createElement('div'); const blogPostTitle = document.createElement('h2'); const authorName = document.createElement('h6'); const authorPost = document.createElement('p'); // 正确创建img元素 const authorImg = document.createElement('img'); // 给图片添加alt属性提升可访问性 authorImg.alt = `博客帖子图片:${title}`; // 添加内容 blogPostTitle.innerText = `Blog post title: ${title}`; authorName.innerText = `Author name: ${author}`; authorPost.innerText = `post: ${text}`; // 给img设置正确的图片地址 authorImg.src = image; // 添加到DOM postDiv.append(blogPostTitle, authorName, authorPost, authorImg); displayPostsCont.appendChild(postDiv); } posts.forEach(createBlogPostElement);
额外优化说明
- 补全了
addPost函数的基础逻辑,现在调用它可以直接把新帖子加入数组并渲染到页面。 - 给图片添加了
alt属性,符合网页可访问性规范。 - 用模板字符串替代字符串拼接,代码更简洁易读。
内容的提问来源于stack exchange,提问作者Kam
相关产品推荐
相关产品推荐

