我正在尝试制作旋转木马。现在我正在开发一个功能,当您单击指标时,会确定指标的索引并将其更改为具有相应索引的图片。该功能有效,但将来,当您单击任何其他指标时,什么都不会发生。包括。无法通过开发人员工具捕获错误。问题是什么?
let imageIndex = 0;
//array with photo
const picArr = [
'golden-retriever-puppy.jpg',
'Drathaar.jpg',
"beagle.jpg",
'alabay.jpg',
'rizenshnautser.jpg',
'Airedale.jpg',
];
showImage(imageIndex, pictureBlock);
function showImage(imageIndex, containerElement){
containerElement.style.backgroundImage = "url(" +picArr[imageIndex]+ ")";
//get list of indicators
let indItems;
const indicatorList = document.getElementById('indicatorList');
if(indicatorList) {
//delete list of indicators
divIndicator.removeChild(indicatorList);
}
//create new element with other picture
indItems = document.createElement('ul');
divIndicator.appendChild(indItems);
indItems.setAttribute('id', 'indicatorList');
for (let i = 0; i < picArr.length; i++){
const item = document.createElement('li');
indItems.appendChild(item);
item.setAttribute('data-order', i);
}
//change colour of running indicator item
indItems.childNodes[imageIndex].setAttribute('id', 'start');
}
function defineIndicatorNumber(e){
console.log(Number(e.target.getAttribute('data-order')));
imageIndex = Number(e.target.getAttribute('data-order'));
showImage(imageIndex, pictureBlock);
}
const indicatorButton = document.querySelectorAll('li');
indicatorButton.forEach(item => item.addEventListener('click', defineIndicatorNumber));
感谢您的帮助,我重写了重新创建的循环,如下所示:
for (let i = 0; i < picArr.length; i++){
item = document.createElement('li');
indItems.appendChild(item);
item.setAttribute('data-order', i);
let items = document.querySelectorAll('li');
items.forEach(item => item.addEventListener('click', defineIndicatorNumber));
}