首页 > 解决方案 > 只需单击一次按钮即可更改多列中的内容

问题描述

我试图通过单击一个按钮来更改多个列,单击后图像应该更改,标题和短语。我只能将此应用于第一列。我尝试使用 querySelectorAll() 迭代列并在其他论坛中搜索答案。?

是否可以通过单击相同的单个按钮为每列分配不同的随机图像?先感谢您!

const images = ['sandwich', 'cookie', 'monster', 'telegram', 'gym']
const inputName = document.getElementById('input-name');
const inputPhrase = document.getElementById('input-phrase');
const btnSubmit = document.querySelector('.input-btn'); 
const btnClr = document.querySelector('.clr-btn'); 


const row = document.querySelectorAll('.column');
const image = document.querySelector('.column img'); 
const title = document.querySelector('.name');
const phrase = document.querySelector('.phrase');

randomImage = Math.floor(Math.random() * images.length);
logoImage = images[randomImage];

window.addEventListener('DOMContentLoaded', function() {
    // createLogo()
})


btnSubmit.addEventListener('click', function(e) {
    e.preventDefault()
    row.forEach(function(col) {
        col.classList.add('change');
        image.src =  `./images/${logoImage}.png`; 
        title.textContent = inputName.value
        phrase.textContent = inputPhrase.value
    })
});

标签: javascripthtmlcss

解决方案


而不是使用变量来引用图像/名称/短语,您应该在每次迭代中col引用它们。queryselector

btnSubmit.addEventListener('click', function(e) {
    e.preventDefault()
    row.forEach(function(col) {
        randomImage = Math.floor(Math.random() * images.length);
        col.classList.add('change');
        col.querySelector("img").src =  './images/' + images[randomImage] + '.png'; 
        col.querySelector(".name").textContent = inputName.value
        col.querySelector(".phrase").textContent = inputPhrase.value
    })
});

推荐阅读