简体   繁体   中英

Can't get ATTR value from IMG SRC using EACH (jquery)

The 'each' function returns 3 times undefined while I am trying to get 3 different results with 3 different URLS.

var src = $('img').each(function(){
    $(this).attr("src");
alert(src);
    });

I found a couple of answer on SO but none of them seems to answer this (really basic) problem.

What I want to do is replace every img url with a more specific URL

ex:

a.jpg --> a-ok.jpg
b.jpg --> b-ok.jpg
c.jpg --> c-ok.jpg

That's why I need the URL of all the img using an EACH.

Please help.

Thanks

Your code is wrong. By assigning src variable to $('img').each you will get elements collection, not src attributes.

Should be:

$('img').each(function(){
  var src = $(this).attr("src");
  alert( src );
});

To replace src attributes you will need do this inside each callback function.

For example like this:

$('img').each(function(){
  var src = $(this).attr("src");
  $(this).attr("src", src.replace('.', '-ok.'));
});
$('img').each(function(){
  var src = $(this).attr("src");
  console.log( src );
  // now override the src 
  var pos = src.lastIndexOf("."); // there can be numerous . in the url
  $(this).attr('src', ( src.substring(0,pos) + '-OK.'+src.substring(pos+1) ) ) ;
});

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