我有一系列图像
var moniqueThumbs = document.getElementsByClassName('moniqueThumbs');
现在我使用点击功能来选择被点击的元素。
for (var i = 0; i < moniqueThumbs.length; i++) {
moniqueThumbs[i].addEventListener("click", grabBigImgPath);
}
现在如何保存单击项的当前索引?
function grabBigImgPath() {
var currentItemclicked=this;
}
我的意思是保存currentItemclicked的索引???
最佳答案
您可以使用类似
var moniqueThumbs = [].slice.call(document.getElementsByClassName('moniqueThumbs')); //using the slice to convert the HTMLCollection to a real array
for (var i = 0; i < moniqueThumbs.length; i++) {
moniqueThumbs[i].addEventListener("click", grabBigImgPath);
}
function grabBigImgPath() {
var index = moniqueThumbs.indexOf(this)
//then use the Array.indexOf() to get the index
snippet.log('clicked: ' + index)
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div class="moniqueThumbs">1</div>
<div class="moniqueThumbs">2</div>
<div class="moniqueThumbs">3</div>
<div class="moniqueThumbs">4</div>
<div class="moniqueThumbs">5</div>