Javascript Array.prototype.map.call不适用于getElementsByClassName对象
我正在尝试制作一个简单的chrome扩展,但是Javascript Array.prototype.map.call不适用于getElementsByClassName对象,javascript,google-chrome-extension,ecmascript-6,Javascript,Google Chrome Extension,Ecmascript 6,我正在尝试制作一个简单的chrome扩展,但是Array.prototype.map.call似乎没有被调用控制台.log(img)不显示任何内容。 我使用getElementsByTagName('img')而不是getElementsByClassName测试了我的代码,它可以正常工作 有什么问题吗 编辑:整个代码: class_name = document.getElementsByClassName('image'); const map = fn => x => Arra
Array.prototype.map.call
似乎没有被调用<代码>控制台.log(img)不显示任何内容。
我使用getElementsByTagName('img')
而不是getElementsByClassName
测试了我的代码,它可以正常工作
有什么问题吗
编辑:整个代码:
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);
虽然
getElementsByClassName()
的返回可能是类似于数组的对象,但很可能它不是真正的数组。今天早上我在尝试调用Element.children对象上的findIndex()时遇到了这个问题。结果表明,这是一个节点列表,而不是实际的数组。不过,通过使用新的Array.from()
方法,我可以绕过它,如下所示:
const index=Array.from(parent.children.findIndex(item=>item.classList.contains('placeholder'))代码>
尝试使用Array.from()
,看看您的问题是否得到解决。页面上是否有类为“image”的元素?你确定它们是img元素吗?是的,我使用console.log()
检查是否有名为“image”的类。代码看起来应该可以正常工作:类“image”不是img元素,它是一个锚标记,类名为“image”,类名为img元素child@YunikMaharjan对我有用:谢谢,但没用。我试着调试,我发现`Array.prototype.map.call(x,fn);`甚至连电话都没有。这里变量“x”是数组。from(class_name)
刚刚做了一些测试,document.getElementsByClass()确实返回了一个类似数组的对象,但是如果不先使用Array.from(),就不能对它运行数组函数。我试图理解您试图用map()函数做什么。Array.map()基于在现有数组的每个元素上处理的函数创建一个新数组,即const map=Array.from(class_name).map(item=>doit(item))
。您的代码看起来好像只是试图在引用的每个项上设置一个事件侦听器,这不是map()的用法,而是forEach()的一个好例子(转换为真数组后)。Array.from(class_name).forEach((el)=>{el.addEventListener('mouseover',(evt)=>dosomething(evt));};
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();
}