2014-04-10 64 views
0
<!DOCTYPE html> 
<html> 
<body> 

<img id="image" src="smiley.gif" width="160" height="120"> 

<script> 
function myFunction() 
{ 
    var img = document.getElementById("image"); 
    if (img.src == "smiley.gif") 

    document.getElementById("image").src="landscape.jpg"; 
    else 
    document.getElementById("image").src="smiley.gif"; 
} 
</script> 
<button type="button" onclick = "myFunction()"> click me </button> 
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p> 

</body> 
</html> 

我想让HTML页面在每次用户点击按钮时在两张图片之间切换,但图片永远不会改变。为什么下面的代码不能按预期执行?

当我改变

if (img.src == "smiley.gif") 

if (img.src.match("smiley.gif")) 

然后代码工作正常。

请问谁能让我知道原因?

+4

的文件名是只存储在'src' ......这就是它的完整URL的一部分。因此,即使您将'src'设置为文件名,它也会存储完整的URL – devnull69

+1

要查看原因,请在'if ...'之前添加'alert(img.src)'以查看'img.src中的实际内容'。 –

+0

@ devnull69谢谢男人!我认为这可能是我错过的观点。 – bean

回答

2

devnull69是对的。如果将img的源设置为相对路径,则它的src属性仍将返回完整的URL。您需要完全限定图像的路径,或者将img.src的值剥离为最终组件(文件名)并进行比较。

例如,你可以这样做:

var imgFilename = img.src.substring(img.src.lastIndexOf("/") + 1); 
if (imgFilename === "smiley.gif") { 
    // Do something. 
} 
相关问题