开发者

Checking if src of img contains certain text with jQuery

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开发者_StackOverflow社区 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜