Один из подходов к проблеме состоит в том, чтобы вместо того, чтобы скрывать и показывать элементы (который опирается на те элементы, которые уже находятся в DOM, а затем отображать и скрывать их соответствующим образом, сохраняя их первоначальный порядок), вставлять соответствующие элементы <img />
при щелчке по элементам <button>
.
В приведенном ниже HTML я убрал большую часть посторонних HTML, чтобы упростить пример, и преобразовал ваши элементы <input type="button" />
в <button>
элементов, что позволяет этим элементам содержать HTML и позволяет использовать сгенерированный контент в псевдоэлементах ::before
и ::after
:
// here we select all <button> elements that have a "data-src"
// attribute:
const buttons = document.querySelectorAll('button[data-src]'),
// creating a named function to handle inserting the
// elements:
insertImage = function() {
// the 'this' is passed automatically from the later
// use of EventTarget.addEventListener() method, here
// we cache that within a variable:
let clicked = this,
// we retrieve the element, via its id, into which
// we wish to append the elements:
output = document.getElementById('gallery'),
// we create an <img> element:
image = document.createElement('img');
// we use a template literal to set the 'src'
// property-value to the 'https' protocol
// coupled with the data-src attribute-value
// retrieved via the Element.dataset API:
image.src = `https://${clicked.dataset.src}`;
// and append the <img> to the desired element:
output.append(image);
};
// here we iterate over the NodeList of <button> elements
// retrieved earlier, using NodeList.prototype.forEach():
buttons.forEach(
// along with an Arrow function to the attach the
// insertImage function (note the deliberate lack of
// parentheses) via the EventTarget.addEventListener()
// method:
(btn) => btn.addEventListener('click', insertImage)
);
/*
using the ::before pseudo-element, with generated
content, to add text to the button elements that
have a data-src attribute:
*/
button[data-src]::before {
content: 'Show image ' attr(value);
}
#gallery {
display: grid;
grid-template-columns: repeat(auto-fill, 180px);
grid-gap: 1em;
align-content: center;
justify-content: center;
}
<!--
here we have three <button> elements, each with a data-src
custom attribute that contains the src of the relevant image:
-->
<button type="button" value="A" data-src="i.stack.imgur.com/4CAZu.jpg"></button>
<button type="button" value="B" data-src="i.stack.imgur.com/SqYhm.gif"></button>
<button type="button" value="C" data-src="i.stack.imgur.com/a9xXV.png"></button>
<div id="gallery"></div>