[問題] jQuery設定img屬性失敗
在書裡看到一個更換圖片的範例
但是做出來都看不到圖片
我發現那行alert的結果是0
所以圖片的大小是0, 0
是不是當時圖片還沒跑完啊?
**HTML**
<div>
<img src="images/green_small.jpg" width="70" height="70" id="photo">
</div>
**JS**
$(document).ready(function() {
var newPhoto = new Image();
newPhoto.src = 'images/green.jpg';
alert(newPhoto.width);
var photo = $('#photo');
photo.attr({
src: newPhoto.src,
width: newPhoto.width,
height: newPhoto.height
});
}); // end ready
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.100.122.142
推
03/08 19:20, , 1F
03/08 19:20, 1F
→
03/08 19:22, , 2F
03/08 19:22, 2F
→
03/08 19:22, , 3F
03/08 19:22, 3F
改成這樣就可以了! 書上都沒說> <
$(document).ready(function() {
var newPhoto = new Image();
newPhoto.src = 'images/green.jpg';
$(newPhoto).load(function() {
$('#photo').attr({
src: newPhoto.src,
width: newPhoto.width,
height: newPhoto.height
}); // end attr
}); // end load
}); // end ready
※ 編輯: acjo 來自: 122.100.122.142 (03/08 19:56)