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"))
然后代码工作正常。
请问谁能让我知道原因?
的文件名是只存储在'src' ......这就是它的完整URL的一部分。因此,即使您将'src'设置为文件名,它也会存储完整的URL – devnull69
要查看原因,请在'if ...'之前添加'alert(img.src)'以查看'img.src中的实际内容'。 –
@ devnull69谢谢男人!我认为这可能是我错过的观点。 – bean