简体   繁体   中英

On dom ready, get all data-src from <img>'s and set them in the src attribute

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>

Since version 1.4.3 or so, jQuery has understood "data-" attributes directly. So just do this:

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

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.

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

Or a little quicker with getAttribute() .

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

If you really want to remove the data-src , then chain .removeAttr('data-src') to the end.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM