我遇到以下代码的问题:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="container"></div>
<script>
var html = "";
var imagesArr = [
"https://2.bp.blogspot.com/-RHUhIkxWXfM/V0knRDiexII/AAAAAAAAAok/gBHYhd4KheAlaPX_LF6rDHkPZ9B4YS6VACLcB/s1600/napolo%2B25%2Bjp.jpg",
"https://4.bp.blogspot.com/-0rDtgu8yH2A/V0knhAVCgyI/AAAAAAAAAoo/zwno2cyB50UKWAlPM41zL--o7OrAKCWHQCLcB/s1600/nike%2B25jp.jpg",
"https://4.bp.blogspot.com/-_w5bgf-rTag/V0knJckJ6II/AAAAAAAAAog/NgHKMdhlCCw9his5PGPhPcFRRdwDzTgXACLcB/s1600/jordan25jp.jpg" ];
for ( var i = 0; i < imagesArr.length; i++ ) {
html += "<div><img src=\"" + imagesArr[ i ] + "\" id=\"img_" + i + "\"></div>";
$( "#img_" + i ).off();
$( "#img_" + i ).on( "load", function() {
console.log( "#img_" + i + " is loaded! Its size is: " + $( "#img_" + i ).width() + "x" + $( "#img_" + i ).height() );
} );
}
$( "#container" ).html( html );
</script>
</body>
</html>
我使用最新版本的JQuery和最新版本的Google Chrome(MacOS Sierra)。我尝试使JQuery的加载事件工作,但在我的控制台中我什么也得不到。代码有什么问题?
答案 0 :(得分:2)
试试这个;)
在将事件添加到DOM
;
for (var i = 0; i < imagesArr.length; i++) {
html += "<div><img class="sizeAfterLoad" src=\"" + imagesArr[ i ] + "\" id=\"img_" + i + "\"></div>";
}
$("#container").html(html);
$(function(){
$(".sizeAfterLoad").off('load').on('load', function() {
console.log("#" + $(this).attr('id') + " is loaded! Its size is: " + $(this).width() + "x" + $(this).height());
});
});