答案很好,但它引入了一个问题。每当您分配或直接分配时,它都可能替换之前分配的回调。这就是为什么有一个很好的方法,“在事件目标上注册指定的侦听器,它被调用”,就像他们在MDN上所说的那样。您可以在同一事件上注册任意数量的侦听器。onload
onerror
让我稍微重写一下答案。
function testImage(url) {
var tester = new Image();
tester.addEventListener('load', imageFound);
tester.addEventListener('error', imageNotFound);
tester.src = url;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
由于外部资源加载过程是异步的,因此使用带有承诺的现代JavaScript会更好,例如以下内容。
function testImage(url) {
// Define the promise
const imgPromise = new Promise(function imgPromise(resolve, reject) {
// Create the image
const imgElement = new Image();
// When image is loaded, resolve the promise
imgElement.addEventListener('load', function imgOnLoad() {
resolve(this);
});
// When there's an error during load, reject the promise
imgElement.addEventListener('error', function imgOnError() {
reject();
})
// Assign URL
imgElement.src = url;
});
return imgPromise;
}
testImage("http://foo.com/bar.jpg").then(
function fulfilled(img) {
console.log('That image is found and loaded', img);
},
function rejected() {
console.log('That image was not found');
}
);