[英]Why doesn't the following Javascript code (to set CSS style) work?
[英]why the following code doesn't perform as expected?
<!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"))
然后代碼按預期工作。
誰能告訴我原因?
devnull69是對的。 如果將img的源設置為相對路徑,則它的src
屬性仍將返回完整的URL。 您需要完全限定圖像的路徑或將img.src
值剝離到最終組件(文件名)並進行比較。
例如,您可以這樣做:
var imgFilename = img.src.substring(img.src.lastIndexOf("/") + 1);
if (imgFilename === "smiley.gif") {
// Do something.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.