2016-03-08 52 views
1

这让我疯狂...... 我从“getElementsByTagName”中创建了一个数组。现在,通过使用“this”方法返回该数组的值之一的onclick,我不能使用“indexOf”来查找其索引。控制台告诉我“arrayThumbs.indexOf不是函数”。在数组中查找indexOf值

这是代码:

var arrayThumbs = listThumbs.getElementsByTagName("img"); //Makes the array with the img tags 

for(i=0;i<maxFiles-1;i++){ 
    arrayThumbs[i].onclick = function(){ 
     imgSelect = this; //Returns a valid value of the array, so far so good 
     indexThumb = arrayThumbs.indexOf(imgSelect); //Returns an ERROR... 
    }; 
} 

的非常奇怪的是,使用相同的语法在其他阵列这个工作完全...

谢谢!

+0

节点列表是不一个数组 –

+0

什么对象是'arrayThumbs'实际出现在错误点?使用您的浏览器的调试器来检查它。 – dsh

+0

我相信'indexOf'需要一个字符串值,而'imgSelect' mayb不会返回一个字符串... http://www.w3schools.com/jsref/jsref_indexof.asp –

回答

4

document.getElementsByTagName returns an HTMLCollection这是“类似数组”,但不是一个数组,因此没有indexOf函数。将其转换为一个数组,你可以使用Array.from,如果你的浏览器支持:

arrayThumbs = Array.from(arrayThumbs); 

或者你可以使用一个众所周知的技巧将其转换为一个数组:

arrayThumbs = Array.prototype.slice.call(arrayThumbs); 
+1

认为这个问题会是这样的... 谢谢! – cerealex