为何无法通过DOM修改图片src属性?代码问题求助
问题原因与解决方案
核心问题:路径转义错误
JavaScript字符串中,反斜杠\是转义字符,比如\f会被解析为换页符,而非路径中的普通反斜杠。你代码里的图片路径(如"E:\freecodecampprojects\Reviews\fblack.jpg")会被浏览器错误解析,导致无法找到对应图片,自然无法切换头像。
解决步骤
修正路径写法,二选一即可:
- 将路径中的反斜杠替换为正斜杠
/:const reviews = [ { id:1, photo : "E:/freecodecampprojects/Reviews/fblack.jpg", fullname: "Sara John", job: "UX DESIGNER", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", }, { id:2, photo : "E:/freecodecampprojects/Reviews/fkorean.jpg", fullname: "Murakami", job: "GRAPHIC DESIGNER", text: "As designers attempting to creating functional work, oftentimes we are required to make our designs look as finished as possible. For example, if you are designing a brand new website for someone, most times you will have to make sure the prototype looks finished by inserting text or photos or what have you.", }, ]; - 用双反斜杠
\\表示路径中的单个反斜杠(转义后保留原路径结构):const reviews = [ { id:1, photo : "E:\\freecodecampprojects\\Reviews\\fblack.jpg", fullname: "Sara John", job: "UX DESIGNER", text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", }, { id:2, photo : "E:\\freecodecampprojects\\Reviews\\fkorean.jpg", fullname: "Murakami", job: "GRAPHIC DESIGNER", text: "As designers attempting to creating functional work, oftentimes we are required to make our designs look as finished as possible. For example, if you are designing a brand new website for someone, most times you will have to make sure the prototype looks finished by inserting text or photos or what have you.", }, ];
- 将路径中的反斜杠替换为正斜杠
可选优化:使用相对路径
如果图片文件和你的HTML页面在同一项目目录下,推荐用相对路径替代绝对路径,避免系统路径兼容问题。比如假设HTML文件在Reviews文件夹中,图片也在该文件夹下,路径可简化为:photo : "./fblack.jpg"
额外验证点
你的代码中currentItem = 1,对应数组中索引为1的第二个对象,初始<img>的src是第一个对象的图片路径。修正路径后,DOMContentLoaded触发时应该会切换到第二个头像,可通过浏览器控制台查看profileImage.src的实际值,确认路径是否正确。
内容的提问来源于stack exchange,提问作者Gyanendra Mohanty
相关产品推荐
相关产品推荐

