如何实现点击按钮反复切换a.jpg与b.jpg?现有代码首次点击后失效
Hey there! The issue here is that once the browser loads the image, the src attribute doesn't stay as the simple relative string "a.jpg" or "b.jpg" — it gets converted to a full absolute URL (like http://your-local-server/a.jpg). So your string comparison fails after the first click, because you're trying to match a full URL to a short filename.
Here are a few solid fixes to get the toggle working repeatedly:
Fix 1: Track the current image with a variable (cleanest approach)
Use a dedicated variable to keep track of which image is displayed, instead of relying on the src attribute's value:
<!DOCTYPE html> <html> <body> <img id="image" src="a.jpg"> <br><br> <script> // Initialize state to track which image is active let currentImage = "a"; function changeImg() { const imgElement = document.getElementById("image"); if (currentImage === "a") { imgElement.src = "b.jpg"; currentImage = "b"; } else { imgElement.src = "a.jpg"; currentImage = "a"; } } </script> <button onclick="changeImg()">Change Image</button> </body> </html>
Fix 2: Extract the filename from the full URL
If you prefer not to use an extra variable, you can extract just the filename part from the absolute src URL:
<!DOCTYPE html> <html> <body> <img id="image" src="a.jpg"> <br><br> <script> function changeImg() { const imgElement = document.getElementById("image"); // Split the URL by slashes and grab the last part (the filename) const currentFilename = imgElement.src.split('/').pop(); imgElement.src = currentFilename === "b.jpg" ? "a.jpg" : "b.jpg"; } </script> <button onclick="changeImg()">Change Image</button> </body> </html>
Fix 3: Use a data attribute to store state
You can also attach a custom data attribute to the image element to track its current state:
<!DOCTYPE html> <html> <body> <img id="image" src="a.jpg" data-current-image="a"> <br><br> <script> function changeImg() { const imgElement = document.getElementById("image"); const currentState = imgElement.dataset.currentImage; if (currentState === "a") { imgElement.src = "b.jpg"; imgElement.dataset.currentImage = "b"; } else { imgElement.src = "a.jpg"; imgElement.dataset.currentImage = "a"; } } </script> <button onclick="changeImg()">Change Image</button> </body> </html>
All these approaches avoid the absolute URL problem and will let you toggle between the two images as many times as you want. The first method is usually the most readable and maintainable for simple cases like this.
内容的提问来源于stack exchange,提问作者Peng

