你可以这样做
var imageTest = $("<img>");
imageTest.attr('src', img_url).load(function() {
alert("image exists");
$("#content").html(image + text); // <-- move it here - if loaded successfully add it
}).error(function() {
alert("image doesn't exist");
imageTest.remove(); // <-- don't need this since it's not even in the dom
$("#content").html(text); // <-- move it here - if failed then just add text
});
虽然我注意到您可能会得到 [Object object].. 您可以使用 append 代替,否则您必须将对象转换为 String
var text = "test text";
var imageTest = $("<img>");
imageTest.attr('src', 'http://dummyimage.com/300').load(function () {
alert("image exists");
$("#content").empty().append(imageTest).append(text); // <-- move it here - if loaded successfully add it
}).error(function () {
alert("image doesn't exist");
imageTest.remove(); // <-- don't need this since it's not even in the dom
$("#content").html(text); // <-- move it here - if failed then just add text
});
小提琴
或者将其转换为字符串
var text = "test text";
var imageTest = $("<img>");
imageTest.attr('src', 'http://dummyimage.com/300').load(function () {
alert("image exists");
var img = $('<div/>').append(imageTest.clone()).html(); // get it as a String
$("#content").html(img + text); // <-- move it here - if loaded successfully add it
}).error(function () {
alert("image doesn't exist");
imageTest.remove(); // <-- don't need this since it's not even in the dom
$("#content").html(text); // <-- move it here - if failed then just add text
});
小提琴