首页 > 解决方案 > 如何在 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>`;
    }
  }

标签: javascripthtmlcss

解决方案


使用img: imgMalemyContacts[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>


推荐阅读