使用javascript加载图片

时间:2017-09-09 10:22:05

标签: javascript jquery

我的照片如下所示:

<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/c/cf/Frog_on_river_4000x3000_26-09-2010_11-01am_2mb.jpg"> </img>

我正在尝试在图像完全加载时获取控制台信息。所以我在下面写了一些东西:

document.querySelector("img").onload = function() {
  console.log('new image loaded: ' + this.getAttribute("src"));
};
不幸的是,它没有像我期望的那样工作。我也试过jQuery加载函数,但它现在被删除所以这个代码有什么问题或者我错过了什么?

3 个答案:

答案 0 :(得分:1)

首先,图片具有自闭标签,因此不需要</img>,只需<img ... />。其次,使用querySelectorAll获取所有图像,并为每个图像添加onload事件监听器:

&#13;
&#13;
var imgs = document.querySelectorAll("img");
imgs.forEach((img) => 
    img.onload = function() {
        console.log('new image loaded: ' + this.getAttribute("src"));
    }
);
&#13;
<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/c/cf/Frog_on_river_4000x3000_26-09-2010_11-01am_2mb.jpg"/>
<img id="myImg2" src="http://placeskull.com/600/600"/>
<img id="myImg3" src="http://placeskull.com/300/300"/>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

<img src="https://upload.wikimedia.org/wikipedia/commons/c/cf/Frog_on_river_4000x3000_26-09-2010_11-01am_2mb.jpg">

var img = document.querySelector('img').getAttribute('src');
console.log('img', img);

答案 2 :(得分:0)

这是因为ClassOne = function( x, y ) { this.x = x; this.y = y; }; ClassTwo = function( x, y, w, h ) { this.x = x; this.y = y; this.w = w; this.h = h; this.position = new ClassOne( this.x, this.y ); this.x = this.position.x; this.y = this.position.y; } var newObj = new ClassTwo( 10, 20, 30, 40 ); for ( var i = 0; i < 15; i++ ) { newObj.position.x++; console.log( newObj.x ); } 事件不会触发缓存的项目。