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

Jquery 使用父元素的属性设置img src的值,jquery,list,attributes,Jquery,List,Attributes,我有一个产品列表,在使用jquery的每个li元素中,我希望在li元素的img中的属性数据拇指中显示图像。i、 e.在每个li元素中将img src的值设置为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/pd

我有一个产品列表,在使用jquery的每个li元素中,我希望在li元素的img中的属性数据拇指中显示图像。i、 e.在每个li元素中将img src的值设置为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加载到其中。加载后,替换内部的
    url。因此,在加载图像时,微调器应显示,然后应将其替换为实际图像(现在从浏览器缓存加载)。

    您可以这样做


    哇,工作得很好,希望我能更好地理解它,你介意解释一下代码吗?非常感谢!好的,我现在有点明白了,谢谢,就几件事。为什么你必须在el变量前加上$?为什么在这行代码$el.find('img')[0].src=url;您必须包括[0]吗?谢谢@user1937021我很高兴它成功了!
    $el
    中的
    $
    只是变量名的一部分。当变量应该包含一个jQuery对象(而不是一个裸DOM节点)时,我通常用
    $
    作为变量名的前缀。在
    [0]
    中,我在做一个类似于oposite的操作:
    $el.find('img')
    可能包含多个图像,我得到的是表示第一个图像的DOM节点。然后,我直接更改了它的
    src
    属性(注意,我没有使用
    .attr
    )。@user1937021我还为上面的代码添加了一些注释,以使其更清晰。
    $('li.product').each(function() {
        var $this = $(this);
        $this.find("img").attr("src", $this.data("thumb"))
    });