我写了JS来克隆图像并将此动作附加到按钮上。
它有效,但是我不确定这种更好的方法。
我的问题:
(function() {
'use strict';
document.querySelector('button[action="button"]').addEventListener('click', function() {
let image = document.querySelector('img[alt="Dog"]');
let cln = image.cloneNode(true);
document.getElementById('image-section').appendChild(cln);
});
})();
<body>
<div id="overview">
<section class="section--center">
<button action="button">Yeah, I want more dogs!</button>
</section>
<section class="section--center" id='image-section'>
<img src="https://www.purina.com/sites/g/files/auxxlc196/files/styles/kraken_generic_max_width_480/public/HOUND_Beagle-%2813inch%29.jpg?itok=lN915WHC" alt="Dog" style="width: 150px">
</section>
</div>
</body>
答案 0 :(得分:0)
另一个选择是更新innerHTML,但这并不好。 一种方法应该解决任务,因此取决于任务。
(function() {
'use strict';
document.querySelector('button[action="button"]').addEventListener('click', function() {
document.getElementById('image-section').innerHTML +=
document.querySelector('img[alt="Dog"]').outerHTML;
});
})();
<body>
<div id="overview">
<section class="section--center">
<button action="button">Yeah, I want more dogs!</button>
</section>
<section class="section--center" id='image-section'>
<img src="https://www.purina.com/sites/g/files/auxxlc196/files/styles/kraken_generic_max_width_480/public/HOUND_Beagle-%2813inch%29.jpg?itok=lN915WHC" alt="Dog" style="width: 150px">
</section>
</div>
</body>