猿问

无法获取单击的幻灯片的正确索引

我正在为滑块编写此函数,当我单击幻灯片时我想获取其索引。


当我记录时,clickedSlide它输出正确的幻灯片,但由于某种原因clickedSlideIndex只返回奇数索引号(1、3、5 等)


slides.forEach(slide => slide.onclick = handleSlideClick);


function handleSlideClick() {

    let clickedSlide = event.target;

    let clickedSlideIndex = Array.prototype.indexOf.call(clickedSlide.parentNode.childNodes, clickedSlide);


    // some stuff..

}

我缺少什么?


MYYA
浏览 95回答 2
2回答

Qyouu

奇数索引号可以通过以下示例来解释:document.getElementById('slides').onclick=handleSlideClick;function handleSlideClick() {&nbsp; let clickedSlide = event.target;&nbsp; let clickedSlideIndex= Array.prototype.indexOf.call(clickedSlide.parentNode.childNodes, clickedSlide);&nbsp; console.log(clickedSlide,clickedSlideIndex);}.slide {display:inline-block}<div id="slides">&nbsp;<div class="slide">one</div>&nbsp;&nbsp;<div class="slide">two</div>&nbsp;&nbsp;<div class="slide">three</div>&nbsp;&nbsp;<div class="slide">four</div>&nbsp;&nbsp;<div class="slide">five</div>&nbsp;&nbsp;<div class="slide">six</div>&nbsp;</div>这里每个节点div.slide后面都有一个&nbsp;(“非换行空格”)节点。在索引计数中,这个小实体也很重要!如果你想避免这种情况发生,你可以替换.childNodes为.children:document.getElementById('slides').onclick=handleSlideClick;function handleSlideClick() {&nbsp; let clickedSlide = event.target;&nbsp; let clickedSlideIndex= Array.prototype.indexOf.call(clickedSlide.parentNode.children, clickedSlide);&nbsp; console.log(clickedSlide,clickedSlideIndex);}.slide {display:inline-block}<div id="slides">&nbsp;<div class="slide">one</div>&nbsp;&nbsp;<div class="slide">two</div>&nbsp;&nbsp;<div class="slide">three</div>&nbsp;&nbsp;<div class="slide">four</div>&nbsp;&nbsp;<div class="slide">five</div>&nbsp;&nbsp;<div class="slide">six</div>&nbsp;</div>

慕斯709654

你可以这样尝试slides.forEach((slide, index) => {&nbsp; &nbsp;slide.onclick = () => handleSlideClick(index)});function handleSlideClick(index) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;console.log(index) // prints the index&nbsp; &nbsp; // some stuff..}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答