[英]Checking if src of img contains certain text with jQuery
我正在寻找使用jQuery 包含来遍历页面上的每个图像,并检查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;
}
});
我觉得正则表达式可能是一种不确定的方式。
我会做(使用indexOf ):
$('img').each(function(i){
var imgSrc = this.src;
var siteURL = "http://url.com";
if(imgSrc.indexOf(siteURL) === -1){
imgSrc = siteURL + imgSrc;
}
});
为什么不简单地使选择器做到这一点呢?
$('img[src*="http://url.com"]')
那应该只选择src标记中带有该文本的元素,而不必编写自定义逻辑。
// find all img's without the siteURL, and add it
$('img:not([src^="http://url.com"])').each(function(i){
this.src = siteURL + this.src;
});
你要搜索您imgSrc
字符串,如果它有siteURL
在它的字符串。
indexOf
方法返回子字符串在主字符串中的位置。 如果找不到,则返回-1
:
if (imgSrc.indexOf(siteURL) == -1) {
imgSrc = siteURL + imgSrc;
}
请查看:contains()选择器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.