我在这里是新手(也是JavaScript的新手),所以请原谅我的基本问题。我有一个包含不同图像的HTML页面,这些图像都共享一个类。通过使用getElementsByClassName,我得到一个数组。我想通过使用.map()函数将事件侦听器添加到数组中的每个单元格。
这就是我所拥有的:
window.onload = function(){
var allImgs = document.getElementsByClassName("pft");
var newImgs = allImgs.map(
function(arrayCell){
return arrayCell.addEventListener("mouseover, functionName");
}
);
};
即使我将内部函数更改为不包含事件侦听器的内容,这也始终显示错误“ allImgs.map不是函数”。
我有此代码的另一个版本,我在其中循环浏览window.onload中的数组单元,并将事件侦听器以这种方式添加到它们中的每一个中,并且它可以正常工作。.map()函数为什么不起作用?它不能在window.onload中使用吗?
getElementsByClassName()
返回,HTMLCollection
而不是Array
。您必须先将其转换为JavaScript数组:
allImgs = Array.prototype.slice.call(allImgs);
// or
allImgs = [].slice.call(allImgs);
// or
allImgs = Array.from(allImgs);
stackoverflow.com/questions/222841/…
@ Flawyte Eek,对我来说还行不通。我可能忽略了一些超级基础的知识。这是我得到的:
window.onload = function(){ var allImgs = document.getElementsByClassName("pft"); var newImgs = [].slice.call(allImgs); console.log(newImgs.typeof); newImgs.map( function(arrayCell){ return arrayCell.addEventListener("mouseover, flipOver"); } ); };
@Flawyte对不起,上面评论中的控制台日志仅显示为“ undefined”。它似乎没有变成数组?
@Flawyte Aaagh我自己感到抱歉;我厌倦了addEventListener括号内容(错误的引号)。谢谢!
@Flawyte现代浏览器支持
Array.from
比的浏览器还干净Array.prototype.slice.call
。