[英]How to addEventListener to querySelectorAll and when triggered get element index(or id, value)?
我正在站點菜單中制作背景選擇器,當用戶單擊規范時,它將更改 backgroundImage。 圖像(觸發單選按鈕)。 我想使用 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>
例如我有幾十張圖片
document.querySelectorAll(".select").forEach( item => {
item.addEventListener('click', arrow => {
document.body.style.backgroundImage = `url("${background_list[index]}")`
})})
有什么方法可以找到觸發的索引(id 或 value)? 您將如何為此實現代碼,最簡單的解決方案是什么? 我是 JS 的初學者
在使用這些數組迭代函數時,您可以通過添加額外參數來找到數組中元素的索引(索引是 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.