首页 > 解决方案 > 使用 JavaScript 动态构建页面

问题描述

我有 2 张 HTML 图像。

我想在每个图像下在 JavaScript 中动态添加一个按钮,单击该按钮以隐藏图像,然后再次单击以再次显示该图像。

这个想法是使用:

代码:

<h2>Create a new site</h2>
<p>Site – Manage Sites - New:</p>
<dd><img class="screenshot" width="238" height="222" src="https://picsum.photos/200" alt="screenshot" /></dd>
<p>“What would you like to call the website?”&lt;/p>
<dd><img class="screenshot" width="238" height="222" src="https://picsum.photos/300" alt="screenshot" /></dd>

img.screenshot {
  margin-bottom: 20px;
  margin-top: 20px;
}

.btn-styled {
  font-size: 14px;
  margin: 10px;
  padding: 0 5px;
  line-height: 2;
}


var eScreens = document.querySelectorAll('img.screenshot');

for (var i = 0; i <= eScreens.length; i++) {
    var button = document.createElement("button");
    button.id = "myButton";
    button.innerHTML = "Show";
    button.className = "btn-styled";
    button.style.background = "orange";
    button.addEventListener("click", function() {
    });
    var dd = document.getElementsByTagName("dd")[0];

    dd.appendChild(button);
}

标签: javascripthtmlcssbutton

解决方案


我会将每个图像包装在一个figure元素中,以便每个图像都包含一个图像,当你添加它时,一个按钮。

// Cache the figures
const figures = document.querySelectorAll('figure');

// For each add a button, and attach an event listener
figures.forEach(figure => {
  addButton(figure);
  figure.addEventListener('click', handleClick, false);
});

// Create a button, and add it to the end of
// each figure element
function addButton(figure) {
  const button = '<button>Hide</button>';
  figure.insertAdjacentHTML('beforeend', button);
}

// Because the listener is attached to the figure
// we need to check if the element we clicked was the
// button. We can then get the image, and then
// use a class to toggle its visibility
// and update the text in the button
function handleClick(e) {
  const { nodeName, parentNode, textContent } = e.target;
  if (nodeName === 'BUTTON') {
   const image = parentNode.querySelector('img');
   image.classList.toggle('hide');
   e.target.textContent = textContent === 'Hide' 
     ? 'Show'
     : 'Hide';
  }
}
figure { display: inline-block; margin: 0; }
button { display: block; margin: 0 auto; }
.hide { visibility: hidden; }
<figure>
  <img src="https://dummyimage.com/100x100/ffaaaa/000" />
</figure>
<figure>
  <img src="https://dummyimage.com/100x100/aaffaa/000" />
</figure>
<figure>
  <img src="https://dummyimage.com/100x100/aaaaff/000" />
</figure>


推荐阅读