2 回答
TA贡献1786条经验 获得超11个赞
奇数索引号可以通过以下示例来解释:
document.getElementById('slides').onclick=handleSlideClick;
function handleSlideClick() {
let clickedSlide = event.target;
let clickedSlideIndex= Array.prototype.indexOf.call(clickedSlide.parentNode.childNodes, clickedSlide);
console.log(clickedSlide,clickedSlideIndex);
}
.slide {display:inline-block}
<div id="slides">
<div class="slide">one</div>
<div class="slide">two</div>
<div class="slide">three</div>
<div class="slide">four</div>
<div class="slide">five</div>
<div class="slide">six</div>
</div>
这里每个节点div.slide后面都有一个 (“非换行空格”)节点。在索引计数中,这个小实体也很重要!如果你想避免这种情况发生,你可以替换.childNodes为.children:
document.getElementById('slides').onclick=handleSlideClick;
function handleSlideClick() {
let clickedSlide = event.target;
let clickedSlideIndex= Array.prototype.indexOf.call(clickedSlide.parentNode.children, clickedSlide);
console.log(clickedSlide,clickedSlideIndex);
}
.slide {display:inline-block}
<div id="slides">
<div class="slide">one</div>
<div class="slide">two</div>
<div class="slide">three</div>
<div class="slide">four</div>
<div class="slide">five</div>
<div class="slide">six</div>
</div>
TA贡献1840条经验 获得超5个赞
你可以这样尝试
slides.forEach((slide, index) => {
slide.onclick = () => handleSlideClick(index)
});
function handleSlideClick(index) {
console.log(index) // prints the index
// some stuff..
}
添加回答
举报