我遇到了一个我无法理解的奇怪问题。
我在网页上有正常的图像
<img src="images/logo.png"/> <!-- getting image from root directory -->
我有一些javascript代码来替换图像源
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; image++)
image[num].src = image[num].src.replace("images/pic01.png", "images/other/pic02.png")
}
这段代码工作得很好,虽然我希望它替换的src在我的根目录之外,例如“http://www.servername.com/pic03.png”//(这是一个虚构的URL)试着点击它。
有这种情况发生的原因吗?有办法解决这个问题吗?
答案 0 :(得分:1)
问题是你只是替换原始src的最后一部分。 img标签的src首先看起来像这样:
“http://yourserver.com/images/pic01.png”
...并在用您的外部网址替换“images / pic01.png”后,它看起来像这样:
要避免此问题,您可以尝试:
function imageUpdate() {
var image = document.querySelectorAll("img");
for (var num = 0; num < image.length; num++) {
if (stringEndsWith(image[num].src, "images/pic01.png")) {
image[num].src = "http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png";
}
}
}
function stringEndsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1
}
你的for循环中也有一个错误,你正在递增图像而不是num
分步说明
的imageUpdate()
遍历每个img标记并查看src属性
如果src以“images / pic01.png”结尾,则用新url替换所有src
stringEndsWith()
查找给定后缀的索引(开始在最后可能的位置查找后缀)
后缀可以位于)
如果找到此索引(与-1不同),则返回true,否则返回false
答案 1 :(得分:0)
您指定的目标网址是什么?确保它指向一个绝对地址(保持http://部分在开头)。
如果文件位于同一服务器中,您仍然可以使用相对文件路径,并使用两个点向上移动父文件夹。例如:../ someotherfolder / pic03.jpg
答案 2 :(得分:0)
<script>
function imageUpdate() {
document.getElementById('imageT').src = 'test.jpg';
}
</script>
<img id='imageT' src="images/logo.png"/> <!-- getting image from root directory -->
答案 3 :(得分:0)
您尝试使用的链接出错。实际链接应为:
http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png
这是代码来演示:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
function changeImage() {
document.getElementById('changeThis').src = 'http://www.oecd.org/media/oecdorg/directorates/developmentcentre/Facebook-logo-34x34.png'
}
</script>
</head>
<body>
<img id="changeThis" src="http://www.wartburgseminary.edu/uploadedImages/Resources/small-twitter-icon.jpg">
<input type="button" value="Change" onClick="changeImage()">
</body>
</html>