如何使用JavaScript附加li和link元素

我正在构建一个灯箱,当我单击具有特定于某些图像列表的不同类的div时,我想显示图像列表。灯箱正在工作,当我单击div时,它会出现,但是当我单击“ .work-1”类的潜水表时,问题就出现了,列表显示为字符串而不是实际图片。我来寻求帮助。

    /* Gallery operation*/
const button = document.querySelectorAll('.gallery');
const list = document.createElement('ul');
const lightbox = document.createElement('div');
const parentDiv = document.querySelector('header').parentNode;
const childDiv = document.querySelector('header');
/*const newList =*/
const logo = [
  '<a href="images/logos1.jpg"></a> ','<a href="images/logos2.jpg"></a> ','<a href="images/logos3.jpg"></a> ','<a href="images/logos4.jpg"></a> ',];
const flyer = [
  '<a href="images/logos1.jpg"></a> ',];

button.forEach(function getThem(div){
   div.addEventListener('click',function(){
     const box  = parentDiv.insertBefore(lightbox,childDiv);
     box.id = 'lightbox';
     const newBox = box.appendChild(list);
     function getList(){
               if(e.target.classname === 'work-1'){
          logo.forEach(function(logo){
            var li = document.createElement('li');
            li.innerText = e;
            newBox.append(li);
          });
        }else if(e.target.classname === 'work-2'){
            flyer.forEach(function(flyer){
              var li = document.createElement('li');
              li.innerText = e;
              newBox.append(li);
            });
          }
        };
        box.getList();
        box.classList.add('active');
       console.log(button);

   });
   lightbox.addEventListener('click',e => {
  if (e.target !== e.currentTarget) return
  lightbox.classList.remove('active')
});

hanxuesong1988 回答:如何使用JavaScript附加li和link元素

我认为您的策略不太正确,我想显示的是图片

<img>

代替锚标签

<a href'..>

您可以通过将<img>附加到src='images/something.jpg'到您的li来获得此结果

因此,您想要一个包含所有图片网址的列表:

const logos = [
  'images/logos1.jpg','images/logos2.jpg','images/logos3.jpg','images/logos4.jpg',]

然后尝试添加此内容:

logos.forEach(function(logo){
            var li = document.createElement('li');
            var img = document.createElement('img');
            img.src = logo;
            li.append(img);
            newBox.append(li);
          });

ES6:

logo.forEach((logo) => {
   const li = document.createElement('li');

   const img = document.createElement('img');

   img.src = logo; // set the url of your image like 'images/logos1.jpg'

   li.append(img);

   newBox.append(li);
})
本文链接:https://www.f2er.com/1240184.html

大家都在问