javascript - 如何在 JS 数组中显示图像?
问题描述
我尝试的每一种方法,我收到的要么是欠精细,要么是物品的描述,而不是图片本身。这是我的代码(使用我尝试过的不同方法):
添加显示全部
<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>
<!-- <img id="imgFemale" src="images/female-icon-7897.png">
<img id="imgMale" src="images/person-icon-1687.png"> -->
<script>
const imgFemale ="images/female-icon-7897.png"
const imgMale = "images/person-icon-1687.png"
let myContacts = [
{ Name: "Hubby ", gender: "male", Image: imgFemale.src="images/person-icon-1687.png"},
{ Name: "Mom", gender: "female", img: imgFemale.value },
{ Name: "Shannon", gender: "female", img: [imgFemale].innerHTML },
{ Name: "Dad", gender: "male", img: imgMale },
];
function add() {
console.log("add pressed");
myContacts.push({
id: myContacts.length + 1,
Name: Name.value,
});
}
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-${myContacts[index]}'>
<button class="btn btn-danger" onClick='remove(${index})'> Delete </button>
${myContacts[index].Name} , ${myContacts[index].gender} , ${myContacts[index].img}</div>`;
}
}
解决方案
使用img: imgMale
和myContacts[index].img
const imgFemale ="images/female-icon-7897.png"
const imgMale = "images/person-icon-1687.png"
let myContacts = [
{ Name: "Hubby ", gender: "male", img: "images/person-icon-1687.png"},
{ Name: "Mom", gender: "female", img: imgFemale },
{ Name: "Shannon", gender: "female", img: imgFemale },
{ Name: "Dad", gender: "male", img: imgMale },
];
function add() {
console.log("add pressed");
myContacts.push({
id: myContacts.length + 1,
Name: Name.value,
});
}
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-${myContacts[index]}'>
<button class="btn btn-danger" onClick='remove(${index})'> Delete </button>
${myContacts[index].Name} , ${myContacts[index].gender} , ${myContacts[index].img}</div>
<img src=${myContacts[index].img}/> </div>`;
}
}
showAll()
<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>
推荐阅读
- mongodb - 从谷歌云存储流恢复“mongodump”备份
- java - 如何使用android中的按钮从另一个片段中打开一个片段
- javascript - 在 Javascript 中处理货币
- javascript - 在不改变状态、道具或父级的情况下反应子级渲染
- javascript - 如何通过一台 Express 服务器部署不同的 React Web 应用程序?
- python - Docker 没有保存 Scrapy 蜘蛛的输出文件
- python - 有人可以帮我理解下面的代码吗
- python - 给它空str不会退出无限期while循环
- c - 为什么在没有显式修改的情况下修改内存
- python - 如何将csv文件转换为数据集?