有时候我们可能需要检查一些评论或回复中图片的链接是否为本站链接,如果是外站链接我们就需要把它改回本站链接
具体需求如下:
编写jq代码实现:
检查页面的图片,
1.如果没有链接,加上链接,地址为http://youkuaiyun.com
2.如果有链接,并且是外站链接,地址改为http://youkuaiyun.com
3.不带图片的链接,不处理
具体代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('img').each(function(){ //遍历页面中的每个图片
var tagT = $(this).parent().get(0).tagName;//选择当前元素的上一层元素获取标签
var m1 = $(this).parent();
if(tagT!='A'){//如果上一层元素标签不是A,那么给它包装上一个链接
$(this).wrap('<a href="http://youkuaiyun.com"></a>')
}else{
m1.filter(function(){//判断链接指向域名是不是站内链接,如果是,不替换链接
return this.hostname && this.hostname != location.hostname;
}).attr({href:"http://youkuaiyun.com"});
}
})
})
</script>
<title>无标题文档</title>
</head>
<body>
<p>产品一<br />
<a href="http://taobao.com"><img src="1.jpg" width="220" height="220" /></a></p>
<p>产品2</p>
<p><br /> <a href="http://sohu.com"><img src="2.jpg" /></a></p>
<p><img src="3.jpg" />
<img src="4.jpg" />
</p>
<a href="1.html"><img src="5.jpg" /></a>
<p><a href="http://taobao.com">别动我,我不是图片!</a></p>
</body>
</html>