在 dom 准备好后,从
获取所有 data-src 并将它们设置在 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>
然后继续。
我正在尝试在不使用 jquery 插件的情况下进行异步加载,并使其尽可能简单。
所以我想,当dom准备好并且页面完全加载时,将data-src设置为src。
如果我这样做: console.log($('figure img').attr('data-src'))
我只得到第一张图像。所以它给了我结果: img1.png
那么我怎么说呢,当 dom 准备好所有数字时 >图像> 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>
In a page I have this:
<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>
and goes on.
I am trying to make an async load without using a jquery plugin and make it as simple as possible.
So I thought, when the dom is ready and the page is fully loaded, set the data-src to the src.
If I do this: console.log($('figure img').attr('data-src'))
I get only the first image. so it gives me result: img1.png
So how can I say, when dom ready all the figure > img > data-src to be set as src for that img.
So from this:
<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>
to this:
<figure><img src="img1.png"></figure>
<figure><img src="img2.png"></figure>
<figure><img src="img3.png"></figure>
<figure><img src="img4.png"></figure>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 1.4.3 左右版本开始,jQuery 已经直接理解“data-”属性。因此,只需这样做:
您必须使用
.each()
来分离最初选择的列表中每个元素的处理,以便您执行的操作可以单独使用该元素。Since version 1.4.3 or so, jQuery has understood "data-" attributes directly. So just do this:
You have to use
.each()
in order to separate out the processing of each element in the initially-selected list so that the operation you perform can use that element by itself.或者使用
getAttribute()
更快一点。如果您确实想删除
data-src
,请将.removeAttr('data-src')
链接到末尾。Or a little quicker with
getAttribute()
.If you really want to remove the
data-src
, then chain.removeAttr('data-src')
to the end.