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:
我希望使用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.
我有一种感觉正则表达可能是走的路,只是不知道如何肯定。
5 个解决方案
#1
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;
});
#2
6
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;
}
});
#3
4
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标签中带有该文本的元素,而不必编写自定义逻辑。
#4
1
You'll want to search your imgSrc
string if it has the siteURL
string in it.
如果imgSrc字符串中包含siteURL字符串,您将需要搜索它。
The indexOf
method 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;
}
#5
-1
Please take a look at :contains() Selector.
请看一下:contains()选择器。
http://api.jquery.com/contains-selector/
http://api.jquery.com/contains-selector/
#1
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;
});
#2
6
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;
}
});
#3
4
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标签中带有该文本的元素,而不必编写自定义逻辑。
#4
1
You'll want to search your imgSrc
string if it has the siteURL
string in it.
如果imgSrc字符串中包含siteURL字符串,您将需要搜索它。
The indexOf
method 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;
}
#5
-1
Please take a look at :contains() Selector.
请看一下:contains()选择器。
http://api.jquery.com/contains-selector/
http://api.jquery.com/contains-selector/