我正在尝试获取已放入列表中的跨度元素的索引。因此,我创建了包含所有元素的列表,但是当我尝试获取元素的索引时,通过单击其中一个元素,出现错误“indexOf 不是函数”。我该怎么做才能解决这个问题并获得预期的输出?
var mdr;
window.onload = function() {
mdr = document.getElementsByClassName("lol");
for (let i = 0; i < mdr.length; i++) {
mdr[i].addEventListener("click", haha);
};
};
function haha() {
console.log(mdr.indexOf(this));
};
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
div {
height: 50px;
width: 100px;
background: grey;
display: flex;
align-items: center;
flex-direction: column;
text-align: center;
}
<div class="lol">1</div>
<div class="lol">2</div>
<div class="lol">3</div>
<div class="lol">4</div>
<div class="lol">5</div>
最佳答案
The
getElementsByClassName()
method of Document interface returns an array-like object of all child elements which have all of the given class names.
由于 getElementsByClassName()
返回的结果不是数组,indexOf()
在结果集中不可用。
尝试使用 Spread syntax
:
[...mdr].indexOf(this)
或:与 Array.from()
The
Array.from()
method creates a new, shallow-copied Array instance from an array-like or iterable object.
Array.from(mdr).indexOf(this)
var mdr;
window.onload = function() {
mdr = document.getElementsByClassName("lol");
for (let i = 0; i < mdr.length; i++) {
mdr[i].addEventListener("click", haha);
};
};
function haha() {
console.log(Array.from(mdr).indexOf(this));
};
html, body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
div {
height: 50px;
width: 100px;
background: grey;
display: flex;
align-items: center;
flex-direction: column;
text-align: center;
}
<div class="lol">1</div>
<div class="lol">2</div>
<div class="lol">3</div>
<div class="lol">4</div>
<div class="lol">5</div>
关于javascript - indexOf 不适用于我的 JavaScript 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56913605/