[我想在JS中使用DOM调用数组元素

问题描述 投票:0回答:1

我有两个HTML文件和一个JS文件,所以我将第一个HTML页面中的信息发送到js中的数组,我想在第二个HTML文件中获取此数组。所以我想在第二个页面的Element中创建元素,但是当我在第二个HTML页面中选择一个元素时,它给了我这个错误(Uncaught TypeError:无法设置null HTMLAnchorElement的属性'innerHTML'。)。它是我的代码但是我在数组中有链接,并且(pic1&pic2&pic3&pic4)我没有在此问题中放置图像链接

const infoBTN = document.getElementsByClassName('infoBTN');
const images = document.querySelector('#img');

const arr = [{name: 'Hello' , Work: 'Front End Developer' , date : '3/2/2020'} , {name: 'HI' , Work: 'Back End Developer' , date : '3/2/2020'} , {name: 'Jack' , Work: 'Full Stack Developer' , date : '3/2/2020'}];
for (let i = 0; i < infoBTN.length; i++) {
  infoBTN[i].addEventListener('click', () => {
    images.innerHTML = `
    <img src=${arr.pic1} alt="${arr.name}" class="pic1">
    <img src=${arr.pic2} alt="${arr.name}" class="pic2">
    <img src=${arr.pic3} alt="${arr.name}" class="pic3">
    <img src=${arr.pic4} alt="${arr.name}" class="pic4">
   `
  })
}

HTML代码

<div class="images" id="img"></div>

请帮助我

javascript html arrays dom
1个回答
0
投票

使用索引读取数组的位置:arr [0] .pic1

const infoBTN = document.getElementsByClassName('infoBTN');
const images = document.querySelector('#hichnia');

    const arr = [{name: 'Hello' , Work: 'Front End Developer' , date : '3/2/2020} , 
{name: 'HI' , Work: 'Back End Developer' , date : '3/2/2020} , 
{name: 'Jack' , Work: 'Full Stack Developer' , date : '3/2/2020}];
    for (let i = 0; i < infoBTN.length; i++) {
      infoBTN[i].addEventListener('click', () => {
        images.innerHTML = `
        <img src=${arr[0].pic1} alt="${arr[0].name}" class="pic1">
        <img src=${arr[1].pic2} alt="${arr[1].name}" class="pic2">
        <img src=${arr[2].pic3} alt="${arr[2].name}" class="pic3">
        <img src=${arr[3].pic4} alt="${arr[3].name}" class="pic4">
       `
      })
    }
© www.soinside.com 2019 - 2024. All rights reserved.