【问题标题】:On dom ready, get all data-src from <img>'s and set them in the src attribute在 dom 准备就绪时,从 <img> 获取所有 data-src 并将它们设置在 src 属性中
【发布时间】:2012-02-01 00:55:51
【问题描述】:

在一个页面中我有这个:

<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>

然后继续。

我正在尝试在不使用 jquery 插件的情况下进行异步加载,并使其尽可能简单。

所以我想,当 dom 准备好并且页面完全加载时,将 data-src 设置为 src。

如果我这样做:console.log($('figure img').attr('data-src')) 我只会得到第一张图片。所以它给了我结果:img1.png

那我怎么说呢,当 dom 准备好所有的图 > img > data-src 被设置为那个 img 的 src。

所以从这里开始:

<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>

到这里:

<figure><img src="img1.png"></figure>
<figure><img src="img2.png"></figure>
<figure><img src="img3.png"></figure>
<figure><img src="img4.png"></figure>

【问题讨论】:

    标签: javascript jquery image asynchronous attr


    【解决方案1】:

    从 1.4.3 左右版本开始,jQuery 已经直接理解了“data-”属性。所以就这样做吧:

    $('figure img').each(function() {
      this.src = $(this).data('src');
    });
    

    您必须使用.each() 来分离对初始选定列表中每个元素的处理,以便您执行的操作可以单独使用该元素。

    【讨论】:

    • @Phrogz, Pointy:使用.data() 很简洁,如果您以后需要处理数据,这很好,但如果不需要,使用.attr() 会更快,并且不会创建对数据的不必要的永久引用。
    • ...但是this.src 肯定更好,所以+1。
    • @amnotiam re: using .data() - 我没想到;这是一个很好的观点。这是其中一种情况,我不确定我是否理解为什么一个人会发现自己首先遇到问题......
    • @Pointy:是的,data- 属性似乎对于从服务器发送带有元素的简单字符串最有用。 jQuery.cache 非常适合更复杂的数据,但对于简单的字符串,我宁愿只看属性。最终,一旦兼容性到达那里,我们将使用this.dataset.src
    【解决方案2】:
    $('figure > img').prop('src',function() {
        return $(this).attr('data-src');
    });
    

    或者使用getAttribute() 更快一点。

    $('figure > img').prop('src',function() {
        return this.getAttribute('data-src');
    });
    

    如果你真的想删除data-src,那么将.removeAttr('data-src')链接到最后。

    $('figure > img').prop('src',function() {
        return this.getAttribute('data-src');
    }).removeAttr('data-src');
    

    【讨论】:

    • 我现在正在拍我的额头如此用力,因为我没有接受这个有效的事实。
    • @Pointy:你的意思是函数参数? :)
    • @Phrogz:我敢打赌,使用@Pointy 的this.src 会更快。如果是我,我可能会这样做,因为src 并不真正需要任何 jQuery 修复。但在.attr().data() 之间,我上周做了一些测试,结果.attr() 名列前茅。
    • ...最快肯定会支持老派this.src = this.getAttribute('data-src')
    • @Phrogz:Found the jsPerf。我通过在测试运行之前预先填充jQuery.cache 来支持.data(),但.attr() 仍然排在首位。
    猜你喜欢
    • 2017-12-13
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    相关资源
    最近更新 更多