0

jQuery を使用して画像とテキストの塊をドキュメントに挿入していますが、画像が実際に存在する場合にのみ画像を含めたいです (画像パスは変数でありimg_url、既存の画像を参照する場合と参照しない場合があります)。

これが私のコードの簡略版です:

var text = data.html,
    image = '<img class="myimage" src="' + img_url + '" />';

var imageTest = $("<img>");
    imageTest.attr('src', img_url).load(function() {
        alert("image exists");
    }).error(function() {
        alert("image doesn't exist");
        imageTest.remove();
    });

if (imageTest.length) {
    $("#content").html(image + text);   
} else {
    $("#content").html(text);
}

画像が存在するかどうかに基づいて正しいアラートを受け取りますが、 はimageTest.length常に と評価されるため、画像が壊れていても1常に に挿入されます。#content

どこが間違っていますか?imageTest.remove()読み込みに失敗した場合は画像要素を削除する必要があるため、その長さは0、いいえ?

4

3 に答える 3

1

あなたはこれを行うことができます

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]を取得することに気づきましたが..代わりに追加を使用するか、オブジェクトを文字列に変換する必要があります

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
});

フィドル

于 2013-01-09T22:50:03.110 に答える
1

jquery doumentation によると、.remove() は一致した要素を dom から削除するだけですが、オブジェクト自体は引き続き存在します。あなたはそれを再接続することができます

$('#example').append(imageTest);

imageTest をリセットする必要があります

imageTest = [];
于 2013-01-09T22:52:12.473 に答える
-1

それが常に存在する理由は、イメージがサーバー上に存在しない場合に404​​を返すためです。これは、実際には404が存在します。JQueryはサーバー側で物事を検出できません。PHPまたは使用しているサーバーサイド言語を使用して、存在するかどうかを検出する必要があります。

于 2013-01-09T22:47:22.520 に答える