最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Checking if src of img contains certain text with jQuery - Stack Overflow

programmeradmin0浏览0评论

I am looking to use jQuery contains to run through each image on a page and check if the src tag contains a certain http value. How would I run a check on the text in the src attribute with jQuery or javacript. I have the overview of what I am attempting below:

$('img').each(function(i){
  var img = $(this),
      imgSrc = img.attr('src'),
      siteURL = "";

  if(!imgSrc.contains(siteURL)){
     imgSrc = siteURL + imgSrc;
  }
});                         

I have a feeling regex may be the way to go just don't know how for sure.

I am looking to use jQuery contains to run through each image on a page and check if the src tag contains a certain http value. How would I run a check on the text in the src attribute with jQuery or javacript. I have the overview of what I am attempting below:

$('img').each(function(i){
  var img = $(this),
      imgSrc = img.attr('src'),
      siteURL = "http://url.com";

  if(!imgSrc.contains(siteURL)){
     imgSrc = siteURL + imgSrc;
  }
});                         

I have a feeling regex may be the way to go just don't know how for sure.

Share Improve this question edited Mar 2, 2016 at 3:02 L84 46.3k59 gold badges181 silver badges259 bronze badges asked Aug 31, 2011 at 17:56 jeffreynoltejeffreynolte 3,77911 gold badges42 silver badges65 bronze badges 2
  • Just so you know $.contains Is not for strings, it is for elements. You check if one element is contained within another, not if a string is contained within another. – Chad Commented Aug 31, 2011 at 18:00
  • Thank you @Chad, yes I realize i posted the wrong link. – jeffreynolte Commented Aug 31, 2011 at 18:39
Add a comment  | 

5 Answers 5

Reset to default 6

i'd do (using indexOf):

$('img').each(function(i){
      var imgSrc = this.src;
      var siteURL = "http://url.com";

  if(imgSrc.indexOf(siteURL) === -1){
     imgSrc = siteURL + imgSrc;
  }
}); 

Why not simply make a selector to do that?

 $('img[src*="http://url.com"]')

That should select just the elements with that text in the src tag, without you having to write custom logic.

// find all img's without the siteURL, and add it
$('img:not([src^="http://url.com"])').each(function(i){
  this.src = siteURL + this.src;
}); 

You'll want to search your imgSrc string if it has the siteURL string in it.

The indexOf method returns the position of the substring within the main string. If it's not found, it returns -1:

if (imgSrc.indexOf(siteURL) == -1) {
     imgSrc = siteURL + imgSrc;
}

Please take a look at :contains() Selector.

http://api.jquery.com/contains-selector/

发布评论

评论列表(0)

  1. 暂无评论