我正在尝试在forEach - addEventListener
方法内部获取目标元素的索引。但是要获得我以前认为的那些并不容易。
let contents = document.querySelectorAll('.contents');
let table = document.querySelectorAll('.table');
function eventRegister() {
contents.forEach((items, idx) => {
items.addEventListener('mouseenter', (event) => {
console.log(items[idx]);
console.log(event.target[idx]);
console.log(event.currentTarget[idx]);
console.log(items.index);
console.log(event.target.index);
console.log(event.currentTarget.index); // all of those console.log is firing undefined
if (idx > 4) {
table.classList.remove('shown');
} else {
table.classList.add('shown');
}
});
})
}
.shown {
background-color: orange;
}
<div class="box">
<div class="contents">this</div>
<div class="contents">is</div>
<div class="contents">a</div>
<div class="contents">text</div>
<div class="contents">group</div>
<div class="contents">test</div>
</div>
<div class="table">
<div class="things">a</div>
<div class="things">b</div>
<div class="things">c</div>
<div class="things">d</div>
</div>
我的目标是从contents
获取每个元素的索引,如果其索引大于4,则从shown
中删除类table
。
是否有任何方法可以获取forEach
方法中每个目标元素的索引?
答案 0 :(得分:1)
只需检查idx
是否大于4:
let contents = document.querySelectorAll('.contents');
let table = document.querySelector('.table');
function eventRegister() {
contents.forEach((item, idx) => {
item.addEventListener('mouseenter', () => {
if (idx > 4) {
table.classList.remove('shown');
} else {
table.classList.add('shown');
}
});
});
}
eventRegister();
.shown {
background-color: orange;
}
<div class="box">
<div class="contents">this</div>
<div class="contents">is</div>
<div class="contents">a</div>
<div class="contents">text</div>
<div class="contents">group</div>
<div class="contents">test</div>
</div>
<div class="table">
<div class="things">a</div>
<div class="things">b</div>
<div class="things">c</div>
<div class="things">d</div>
</div>
请注意,forEach
的第一个参数是正在迭代的当前元素,因此您可能应将其命名为item
,而不是items
,以免使自己困惑。 (这不是集合,而是单个元素。)
您还可以使用事件委托,而不是添加很多单独的侦听器:
let contents = document.querySelectorAll('.contents');
let table = document.querySelector('.table');
function eventRegister() {
const box = document.querySelector('.box');
box.addEventListener('mouseover', ({ target }) => {
if (!target.matches('.contents')) {
return;
}
const index = [...box.children].indexOf(target);
if (index > 4) {
table.classList.remove('shown');
} else {
table.classList.add('shown');
}
});
}
eventRegister();
.shown {
background-color: orange;
}
<div class="box">
<div class="contents">this</div>
<div class="contents">is</div>
<div class="contents">a</div>
<div class="contents">text</div>
<div class="contents">group</div>
<div class="contents">test</div>
</div>
<div class="table">
<div class="things">a</div>
<div class="things">b</div>
<div class="things">c</div>
<div class="things">d</div>
</div>