イベント ハンドラー プロパティの正しいスペルは、.onload
ではなく、すべて小文字.onLoad
です。
var img = new Image();
img.onload = function() {
console.log("load"); // works every time
};
img.src = "img/domino/21.png";
Javascript では大文字と小文字が区別されるため、すべてのオブジェクト プロパティに適切な大文字と小文字を使用する必要があります。
その他の代替手段は、.onload
次を使用することです。
img.addEventListener("load", function(e) {...});
または (古いバージョンの IE の場合):
img.attachEvent("onload", function(e) {...});
イベント ハンドラーを 1 つしか使用しておらず、既にイベント ハンドラーを抽象化したクロス プラットフォーム ライブラリを使用していない場合は、使用する.onload
のが最も簡単です。
そして、イベント ハンドラーを追加する簡単なクロス ブラウザーの方法を次に示します。
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}