我是 JS 的新手,需要幫助。我想在每次單擊箭頭時動態更改影像和段落。為此,我有一個陣列,其中包含此影像和此段落在每次點擊時必須采用的不同值。
這是我的桌子:
const slides = [
{
"image":"slide1.jpg",
"tagLine":"Impressions tous formats <span>en boutique et en ligne</span>"
},
{
"image":"slide2.jpg",
"tagLine":"Tirages haute définition grand format <span>pour vos bureaux et events</span>"
},
{
"image":"slide3.jpg",
"tagLine":"Grand choix de couleurs <span>de CMJN aux pantones</span>"
},
{
"image":"slide4.png",
"tagLine":"Autocollants <span>avec découpe laser sur mesure</span>"
}
]
這個想法是:我想創建一個函式來在每次單擊時回圈遍歷我的陣列。
click 1 = object 1 of the array. click 2 = object 2 of the array. click 3 = object 3 of the array. click 4 = return to object 0.
let slide = 0
let currentSlide = slides[slide]
console.log(currentSlide)
// Function to advance in the table slides on click
function loopTableSlides() {
slides.forEach(function(slide, index) {
if ((slides.length - 1) == slide) {
slide = 0 // to return to the first object in the array
} else {
slide = index 1 // to move on to the next item each turn
}
console.log(currentSlide)
})
}
const arrowRight = document.querySelector('.arrow_right')
arrowRight.addEventListener('click', function(e) {
e.stopPropagation()
console.log('arrow right click')
activeBullet()
loopTableSlides()
})
然后我想創建另一個帶有 setAttribute 和 innerHTML 的函式,它將在我的事件偵聽器中呼叫,并將獲取這個著名回圈的值。
附件是我要檢查的第一個函式和有問題的陣列的相應代碼。在控制臺中,它回傳 4 次相同的物件并且始終相同。不幸的是我不明白為什么...
謝謝你的幫助。
uj5u.com熱心網友回復:
你可以這樣做
const slides = [
{
"image":"slide1.jpg",
"tagLine":"Impressions tous formats <span>en boutique et en ligne</span>"
},
{
"image":"slide2.jpg",
"tagLine":"Tirages haute définition grand format <span>pour vos bureaux et events</span>"
},
{
"image":"slide3.jpg",
"tagLine":"Grand choix de couleurs <span>de CMJN aux pantones</span>"
},
{
"image":"slide4.png",
"tagLine":"Autocollants <span>avec découpe laser sur mesure</span>"
}
]
const slide = document.getElementById('slide')
const prev = document.getElementById('prev')
const next = document.getElementById('next')
let index = 0
const showSlide = n => {
slide.innerHTML = slides[n].image
}
showSlide(index)
next.addEventListener('click', () => {
index = (index 1) % slides.length
showSlide(index)
})
prev.addEventListener('click', () => {
index = (index slides.length - 1) % slides.length
showSlide(index)
})
<div id="slide"></div>
<button id="prev" >prev</button>
<button id="next" >next</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535065.html
