如何将EventListener 添加到querySelectorAll 并在触发时获取元素索引(或id、值)?
How to addEventListener to querySelectorAll and when triggered get element index(or id, value)?
我正在站点菜单中制作背景选择器,它会在用户点击规格时更改背景图像。图像(触发单选按钮)。我想使用 querySelectorAll(".selected") 来完成它,循环它并设置 addEventListener(click, ..) get index(or id, value) 并使用 background_list array.
设置 backgroundImage
var background_list = ["/images/air-balloon.jpg","/images/mary-christmas.jpg","/images/mountain.jpg","/images/panorama.jpg","/images/plants.jpg","/images/sunset-mountain.jpg","/images/underwater-star.jpg","/images/vinyl-player.jpg"...]
<div class="dropdown-background-container">
<div>
<input
type="radio"
id="image-1"
class="select"
value="1"
>
<label for="image-1">
<img src="/images/air-balloon-small.jpg" alt="Air Balloons">
</label>
</div>
<div>
<input
type="radio"
id="image-2"
class="select"
value="2"
>
<label for="image-2">
<img src="/images/mary-christmas-small.jpg" alt="Mary Christmas">
</label>
</div>
比如我有几十张图片
document.querySelectorAll(".select").forEach( item => {
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
有没有办法找到触发索引(id 或值)?您将如何为此实现代码,最简单的解决方案是什么?我是 JS 初学者
您可以在使用这些数组迭代函数时通过添加额外参数(索引是 forEach 的第二个参数)找到数组中元素的索引:
document.querySelectorAll(".select").forEach((item, index) => { // here
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
我正在站点菜单中制作背景选择器,它会在用户点击规格时更改背景图像。图像(触发单选按钮)。我想使用 querySelectorAll(".selected") 来完成它,循环它并设置 addEventListener(click, ..) get index(or id, value) 并使用 background_list array.
设置 backgroundImagevar background_list = ["/images/air-balloon.jpg","/images/mary-christmas.jpg","/images/mountain.jpg","/images/panorama.jpg","/images/plants.jpg","/images/sunset-mountain.jpg","/images/underwater-star.jpg","/images/vinyl-player.jpg"...]
<div class="dropdown-background-container">
<div>
<input
type="radio"
id="image-1"
class="select"
value="1"
>
<label for="image-1">
<img src="/images/air-balloon-small.jpg" alt="Air Balloons">
</label>
</div>
<div>
<input
type="radio"
id="image-2"
class="select"
value="2"
>
<label for="image-2">
<img src="/images/mary-christmas-small.jpg" alt="Mary Christmas">
</label>
</div>
比如我有几十张图片
document.querySelectorAll(".select").forEach( item => {
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
有没有办法找到触发索引(id 或值)?您将如何为此实现代码,最简单的解决方案是什么?我是 JS 初学者
您可以在使用这些数组迭代函数时通过添加额外参数(索引是 forEach 的第二个参数)找到数组中元素的索引:
document.querySelectorAll(".select").forEach((item, index) => { // here
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})