class_name = document.getElementsByClassName('image');
const map = fn => x => Array.prototype.map.call(x, fn);
map(img => {
console.log(img);
img.addEventListener('mouseover', (e) => {
global = e.target.src;
calledsomething(global);
});
})(class_name);
我试图制作一个简单的Chrome扩展程序但Array.prototype.map.call
似乎没有被调用。 console.log(img)
没有显示任何内容。
我使用getElementsByTagName('img')
代替getElementsByClassName
测试了我的代码,但它确实有效。
可能是什么问题?
编辑:整个代码:
var isHovered = false;
var global;
const class_name = document.getElementsByClassName('photo_activity_item__img_wrapper');
const map = fn => x => Array.prototype.map.call(x, fn);
console.log(class_name);
map(img => {
img.addEventListener('mouseover', (e) => {
global = e.target.src;
console.log(global);
hoveredBox();
});
img.addEventListener('mouseleave', (e) => {
isHovered = false;
});
})(class_name);
document.addEventListener('keypress', keyDown);
function hoveredBox() {
isHovered = true;
}
function keyDown(event) {
if (!isHovered) return;
var key = event.keyCode;
if (key === 115) {
saveFile(global);
}
}
// Download a file form a url.
function saveFile(url) {
// Get file name from url.
filename = url;
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
console.log(a.href);
console.log(xhr.response);
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
delete a;
};
xhr.open('GET', url);
xhr.send();
}
答案 0 :(得分:0)
虽然getElementsByClassName()
的返回可能是类似对象的数组,但它很可能不是真正的数组。今天早上我试图在Element.children对象上调用findIndex()时遇到了这个问题。原来这是一个NodeList,而不是一个实际的数组。通过使用像这样的新Array.from()
方法,我能够绕过它:
const index = Array.from(parent.children).findIndex(item => item.classList.contains('placeholder'));
试试Array.from()
并查看问题是否已解决。