首页 > 解决方案 > How to change status when clicking on a specific node

问题描述

I'm trying to create a gallery. Most of it already works thanks to some online tutorials. On the final page there should be a slider and also some thumbnails to click on which will effect the slider. I tried to achieve this by working with status. The problem I'm facing right now is to change the status when clicking on the matching img.

const imgs = document.querySelectorAll('.imgs img');
let status = 0;
var num = document.querySelectorAll('.profile_pics img').length;
let maxstatus = status + num;

imgs.forEach(img => img.addEventListener('click', imgClick));

function imgClick(){
  for(let f = 0; f < imgs.length; f++){ 
    if(imgs[f].click == true){
      status = [f];
    }
  }
}

// Rest of the code (is working)

function reset(){
  for(let i = 0; i < maxstatus; i++){
    slides[i].style.display = 'none';
    slides[i].style.opacity = 0;
    slides[i].classList.add('fade_in');
    imgs[i].style.opacity = 1;
  }
}

function focus(){
  imgs[status].style.opacity = opacity;
  }

function startSlide(){
  reset();
  slides[0].style.display = 'block';
}


function slideLeft(){
  reset();
  slides[status - 1].style.display = 'block';
  status--;
  focus()
  console.log(status);
}


function slideRight(){
  reset();
  slides[status + 1].style.display = 'block';
  status++;
  focus()
  console.log(status);
}


prevBtn.addEventListener('click', function(){
  if(status === 0){
    status = maxstatus;
  }
  slideLeft();
});


nextBtn.addEventListener('click', function(){
  if(status === maxstatus - 1){
    status = -1;
  }
  slideRight();
});

startSlide();

I've tried now for a couple of hours but can't find a solution. Worked with console.log of course but simply can't get the status update working when clicking of one of those images.

Help would be appreciated - Thanks a lot

标签: javascriptonclicknodelist

解决方案


完整代码可以在这里找到:粘贴 Bin 链接

更新:

// Global Variable
let status = -1;
let imgs = [
    $('#img0'),
    $('#img1'),
    $('#img2'),
    $('#img3'),
    $('#img4'),
    $('#img5'),
]

// Functions
function imgClick(elm){
    status = imgs.indexOf(elm); // This will set the status variable to the element index, using indexOf function. it will check inside of imgs variable which element index it is, if it cant be found status will return a -1  value
}

// Execute
imgs.forEach(img => img.on('click', () => {
    imgClick(img);  
}));

推荐阅读