使用父元素的属性设置img src的值

我有一个产品列表,在每个带有jquery的li元素中,我想在li元素中的img内的属性data-thumb中显示图像。 即将img src的值设置为每个li元素中data-thumb的值,但在加载时我想显示已存在的ajax-loader.gif。 有人能引导我朝着正确的方向前进吗?

例:

  • 谢谢!

    试试这个:

     // 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。 因此,微调器应该在加载图像时显示,然后应该用实际图像(现在从浏览器的缓存加载)替换。

    你可以做到

     $('li.product').each(function() { var $this = $(this); $this.find("img").attr("src", $this.data("thumb")) });