1

製品のリストがあり、jquery を使用した各 li 要素で、li 要素内の img の属性 data-thumb に画像を表示したいと考えています。つまり、img src の値を各 li 要素の data-thumb の値に設定しますが、読み込み中に既に存在する ajax-loader.gif を表示したいと考えています。誰かが私を正しい方向に導くことができますか?

例:

<li data-id="7" data-thumb="http://test.com/assets/pdc/thumbs/66.png" data-img="http://test.com/assets/pdc/img/66.png" data-country="Australia" data-company="Big Farm" data-app="Tea" data-brand="Big Farm" data-package="500" class="product air-500 cat7">
    <img class="tip" data-country="Australia" data-brand="Big Farm" src="assets/img/ajax-loader.gif">
</li>

ありがとう!

4

2 に答える 2

3

これを試して:

// Loop through all lis with class product
$('li.product').each(function(){
    // grab a reference to the current li
    var $el = $(this);
    // get the url from its data-thumb attribute
    var url = $el.data('thumb');
    // create a new Image element to load into
    var img = new Image();
    // load callback for the new image
    img.onload = function() {
        // find the first image inside the li
        // and change its src to the url we just loaded
        $el.find('img')[0].src = url;
    }
    // set the src of our temp Image to start loading
    img.src = url;
});

コードの背後にある考え方は、DOM に追加されない新しいImage要素を作成し、そこに URL をロードすることです。ロードされたら、内部<img>URL を置き換えます。そのため、画像の読み込み中にスピナーが表示され、実際の画像 (ブラウザーのキャッシュから読み込まれる) に置き換えられます。

于 2013-01-04T18:49:58.773 に答える
0

あなたができる

$('li.product').each(function() {
    var $this = $(this);
    $this.find("img").attr("src", $this.data("thumb"))
});
于 2013-01-04T18:57:25.087 に答える