[英]Result of `document.getElementsByClassName` doesn't have array methods like `map` defined, even though it is an array
我有以下一些代碼來選擇一些div並在它們上面添加一個click處理程序
var tiles = document.getElementsByClassName("tile");
tiles.map(function(tile, i){
tile.addEventListener("click", function(e){
console.log("click!");
});
});
這會引發錯誤,因為即使tiles是一個數組,也沒有定義map
。 如果我這樣做一個數組,那么map工作正常:
var a = [1, 2, 3, 4];
a.map(/*whatever*/);
解決方法是將貼圖附加到貼圖,如下所示:
tiles.map = Array.prototype.map;
這很好用。 我的問題是為什么tiles
沒有定義地圖? 它不是真正的陣列嗎?
對,它不是一個真正的數組。 這是一個“陣列式”。
不要將map
附加到tiles
。 做就是了
Array.prototype.map.call(tiles, function...)
有人可能會建議
Array.prototype.slice.call(tiles).map(function...
哪種歸結為同一件事。 有些人喜歡寫作
[].slice.call(tiles).map(function...
這節省了一些按鍵。
當然,既然你並沒有真正使用map
來返回一個數組,你可以用老式的方式循環:
for (var i = 0; i < tiles.length; i++) {
tiles[i].addEventListener("click", function(e){
console.log("click!");
});
}
另見MDN的解釋 。 雖然這討論了NodeList
,但相同的原則適用於HTMLCollection
,這是getElementsByClassName
返回的內容。
在ES6中,我們有一些更簡單的方法將tiles
轉換為數組,包括
[...tiles]
Array.from(tiles)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.