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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7261259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:29:50  来源:igfitidea点击:

Checking if src of img contains certain text with jQuery

javascriptjqueryhtml

提问by jeffreynolte

I am looking to use jQuery containsto 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:

我希望使用 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;
  }
});                         

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

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

回答by Nicola Peluchetti

i'd do (using indexOf):

我会做(使用indexOf):

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

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

回答by Tejs

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.

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

回答by ken

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

回答by Joseph Silber

You'll want to search your imgSrcstring if it has the siteURLstring in it.

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

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

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

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

回答by renil

Please take a look at :contains() Selector.

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

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

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