javascript - 只需单击一次按钮即可更改多列中的内容
问题描述
我试图通过单击一个按钮来更改多个列,单击后图像应该更改,标题和短语。我只能将此应用于第一列。我尝试使用 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
})
});
解决方案
而不是使用变量来引用图像/名称/短语,您应该在每次迭代中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
})
});
推荐阅读
- c# - 为什么我的对象列表呈现为复选框返回一个空列表?[ASP.NET 核心 - 3.1]
- kubernetes - Kubernetes:使用“envFrom”定义依赖于其他变量的环境变量
- android - 我在颤振代码中有问题。它的给定是 RenderCustomMultiChildLayoutBox 对象在布局期间被赋予了无限的大小
- java - 如何将数组的 JSON 数组添加到模型中
- python - 如何设置整行而不是所有单元格的样式
- github-pages - 如何让 GIF 出现在 Github Pages 帖子上?
- c# - 使用 C# 类完全定义的 Razor 组件的 CSS 隔离
- arrays - 如何对数组求和的循环进行矢量化?
- java - spring boot CLIENT_PLUGIN_AUTH 是必需的,检查mysql版本
- r - 尽管发出 purrr 的“否则”错误 - 为什么没有触发 purrr/可能的“否则”?