我有一个产品列表,并且在每个带有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>
谢谢!
答案 0 :(得分: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
元素,并将其加载到其中。加载后,替换内部<img>
网址。因此微调器应该在加载图像时显示,然后应该用实际图像替换(现在从浏览器的缓存中加载)。
答案 1 :(得分:0)
你可以做到
$('li.product').each(function() {
var $this = $(this);
$this.find("img").attr("src", $this.data("thumb"))
});