如何获取使用香草JS单击的div的索引。 是否有诸如indexOf()或.selectedIndex之类的方法或属性?
function test() {
var div = document.getElementsByTagName('div');
}
div.flex {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
div:hover {
cursor: pointer;
}
<div class="flex">
<div onclick="test()"><img src="http://via.placeholder.com/100x100" alt=""></div>
<div onclick="test()"><img src="http://via.placeholder.com/100x100" alt=""></div>
<div onclick="test()"><img src="http://via.placeholder.com/100x100" alt=""></div>
<div onclick="test()"><img src="http://via.placeholder.com/100x100" alt=""></div>
</div>
答案 0 :(得分:2)
您需要将div作为参数传递,然后使用parent.indexOf(child)
:
function test(el) {
var divs = document.querySelectorAll(".flex div");
var index = Array.from(divs).indexOf(el);
console.log(index);
}
div.flex {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
div:hover {
cursor: pointer;
}
<div class="flex">
<div onclick="test(this)"><img src="http://via.placeholder.com/100x100" alt=""></div>
<div onclick="test(this)"><img src="http://via.placeholder.com/100x100" alt=""></div>
<div onclick="test(this)"><img src="http://via.placeholder.com/100x100" alt=""></div>
<div onclick="test(this)"><img src="http://via.placeholder.com/100x100" alt=""></div>
</div>