Jquery 通过文本检测更改图像源
我目前正在开发一个显示内容的应用程序 我想替换那些选择退出的用户的图像 我的html结构如下:Jquery 通过文本检测更改图像源,jquery,flickr,Jquery,Flickr,我目前正在开发一个显示内容的应用程序 我想替换那些选择退出的用户的图像 我的html结构如下: <ul> <li> <div class="imgbk"> <img src='http://farm6.static.flickr.com/5312/7057785005_2966a34f1f.jpg'/> <a href='http://www.flickr.com/photos/85152114@N00/7
<ul>
<li>
<div class="imgbk">
<img src='http://farm6.static.flickr.com/5312/7057785005_2966a34f1f.jpg'/>
<a href='http://www.flickr.com/photos/85152114@N00/7057785005'>Link</a>
</div>
</li>
</ul>
本例中要测试的字符串是85152114@N00位于href
href结构始终相同:flickr.com/photos/userID/ImageID
到目前为止,这是在服务器端完成的,但我网站上的巨大流量迫使我在客户端完成这项工作。我的jQuery知识有限,所以我请求帮助 不完全确定你在找什么。但是,如果要获取该字符串,可以执行以下操作:
var a = $('.imgbk a').attr('href');
var b = a.split('/');
alert(b[4]);
例如:
基本上,找到href属性,然后在/处对其进行分割,将每个片段放入一个名为b的数组中。我已经通知了结果,以便您可以查看数组中要选择的项目,但您可以从那里对其执行任何操作 如果您正在寻找一种方法来检查页面中所有包含特定代码的项目的图像,您可以这样做
var optOutstr = "85152114@N00";
$(img).each(function() {
if (this.href.match(new RegExp("/" + optOutStr + "/")) {
this.href = "whatever you want to replace the URL with";
$(this).prev().attr("src", "whatever you want to replace the image with");
}
});
如果您有一个完整的代码列表要检查,那么将有更有效的方法来检查一大堆代码
var optOutMap = {"85152114@N00": true, ....};
$(img).each(function() {
var matches = this.href.match(/flickr.com\/photos\/([^\/]+)\//);
if (matches && matches[1] in optOutMap) {
this.href = "whatever you want to replace the URL with";
$(this).prev().attr("src", "whatever you want to replace the image with");
}
});
谢谢各位,以下是我根据你们的答案编写的新代码:
var OptOutArray = ["85152114@N00", "00000000@N00"];
$('img').each(function() {
var matches = $(this).next().attr("href").split('/')[4];
if ($.inArray(matches, OptOutArray) > -1) {
$(this).attr("src", "http://core.flickeflu.com/doh.gif");
}
});
示例如下: