[英]How to addEventListener to querySelectorAll and when triggered get element index(or id, value)?
I'm making background selector in site menu, It will change backgroundImage when user clicks on spec.我正在站点菜单中制作背景选择器,当用户单击规范时,它将更改 backgroundImage。 image (that triggers radio button).
图像(触发单选按钮)。 I want to do it using querySelectorAll(".selected"), loop it and set addEventListener(click, ..) get index(or id, value) and set backgroundImage using background_list array.
我想使用 querySelectorAll(".selected") 来完成它,循环它并设置 addEventListener(click, ..) 获取索引(或 id,值)并使用 background_list 数组设置 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>
For example I have dozens of images例如我有几十张图片
document.querySelectorAll(".select").forEach( item => {
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
Is there any way to find triggered index(id or value)?有什么方法可以找到触发的索引(id 或 value)? And how would you implement code for this, what's easiest solution?
您将如何为此实现代码,最简单的解决方案是什么? I'm beginner in JS
我是 JS 的初学者
You can find the index of an element in an array while using these array iteration functions by adding extra parameters (index is the second parameter with forEach):在使用这些数组迭代函数时,您可以通过添加额外参数来找到数组中元素的索引(索引是 forEach 的第二个参数):
document.querySelectorAll(".select").forEach((item, index) => { // here
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.