2 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
奇數(shù)索引號可以通過以下示例來解釋:
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>
這里每個(gè)節(jié)點(diǎn)div.slide后面都有一個(gè) (“非換行空格”)節(jié)點(diǎn)。在索引計(jì)數(shù)中,這個(gè)小實(shí)體也很重要!如果你想避免這種情況發(fā)生,你可以替換.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貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
你可以這樣嘗試
slides.forEach((slide, index) => {
slide.onclick = () => handleSlideClick(index)
});
function handleSlideClick(index) {
console.log(index) // prints the index
// some stuff..
}
添加回答
舉報(bào)