如何在JavaScript数组中存储图片并正常显示?
修复方案
核心错误原因
- 变量类型误用:你声明的
imgFemale、imgMale本身就是存储图片路径的字符串,不是DOM节点对象,调用.src、.value、.innerHTML都是非法操作,会返回undefined - 字段名不统一:联系人数组里第一个对象的图片字段用了大写开头的
Image,其余用的小写img,取值时无法匹配导致读不到值 - 缺少图片标签:渲染时直接输出图片路径字符串,没有包裹在
<img>标签中,浏览器只会把路径当文本渲染,不会加载图片 - 样式类拼接错误:
alert-${myContacts[index]}直接把整个联系人对象拼接到类名里,语法完全错误,会导致样式失效 - 新增联系人逻辑缺失:当前
add函数仅存储了姓名,没有补充性别、头像属性,后续新增的联系人渲染时仍会出现undefined
修复后完整代码
<label for="Name">Name</label> <input id="Name" /><br /> <button onclick="searchByName()" class="btn btn-info"> Search by Name </button> <input id="Search" /> <label for="Search">Search</label> <br /> <div class="alert alert-primary" id="display"><h1>My Contacts</h1></div> </div> <script> const imgFemale = "images/female-icon-7897.png" const imgMale = "images/person-icon-1687.png" let myContacts = [ { Name: "Hubby ", gender: "male", img: imgMale }, { Name: "Mom", gender: "female", img: imgFemale }, { Name: "Shannon", gender: "female", img: imgFemale }, { Name: "Dad", gender: "male", img: imgMale }, ]; function add() { console.log("add pressed"); // 这里可根据业务补充性别、头像的输入逻辑,现在暂时给默认值避免undefined myContacts.push({ id: myContacts.length + 1, Name: Name.value, gender: "未知", img: imgMale // 可改成默认头像路径 }); } function showAll() { console.log("showAll pressed"); display.innerHTML = "<h1>My Contacts</h1>"; for (let index = 0; index < myContacts.length; index++) { display.innerHTML += `<div class='alert alert-secondary'> <button class="btn btn-danger" onClick='remove(${index})'> Delete </button> ${myContacts[index].Name} , ${myContacts[index].gender} , <img src="${myContacts[index].img}" alt="头像" style="width: 24px; height: 24px; vertical-align: middle;"></div>`; } } </script>
额外说明
如果需要支持新增联系人时自定义性别和头像,可以补充对应的性别单选框、头像选择控件,在add函数中获取对应值存入对象即可。
内容的提问来源于stack exchange,提问作者AYB
相关产品推荐
相关产品推荐

