检查img的src是否包含jQuery的某些文本

时间:2011-08-31 17:56:21

标签: javascript jquery html

我希望使用jQuery contains来浏览页面上的每个图像,并检查src标记是否包含某个http值。如何使用jQuery或javacript对src属性中的文本进行检查。我概述了我在下面尝试的内容:

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

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

我有一种感觉正则表达可能是走的路,只是不知道如何肯定。

5 个答案:

答案 0 :(得分:6)

我会(使用indexOf):

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

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

答案 1 :(得分:4)

为什么不简单地让选择器来做呢?

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

那应该只选择src标签中带有该文本的元素,而不必编写自定义逻辑。

答案 2 :(得分:3)

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

答案 3 :(得分:1)

如果imgSrc字符串中包含siteURL字符串,则您需要搜索该字符串。

indexOf方法返回主字符串中子字符串的位置。如果找不到,则返回-1

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

答案 4 :(得分:-1)

请看一下:contains()选择器。

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