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

标签 jquery list attributes

我有一个产品列表,在带有 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>

谢谢!

最佳答案

试试这个:

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

代码背后的想法是,创建一个新的 Image未附加到 DOM 的元素,并将您的 url 加载到其中。加载完毕后,更换内部<img>网址。因此,微调器应该在加载图像时显示,然后应该将其替换为实际图像(现在从浏览器的缓存中加载)。

关于jquery - 使用父元素的属性设置 img src 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14163004/

相关文章:

java - 对列表 - 字符串元素进行排序

java - 将属性从一个类传递到另一个类+在java中实例化

python - 如何从 python 列表中删除特定索引

javascript - 使用 HTML 输出标签查看可缩放图像并分配 src

c# - 基于属性的项目之间的反射(reflection)

jquery - .prop ('checked' ,false) 或 .removeAttr ('checked' )?

jquery - 如何自定义所需弹出窗口的文本?

javascript - window.location 与相对 url

javascript - 基于 radio 选择的重定向表单

list - 将新项目附加到方案中列表的末尾