我有一个图像 - image1.png。当我第一次单击按钮时,我希望它更改为 image2.png。当我第二次单击该按钮时,我希望它更改为另一个图像 image3.png。
到目前为止,我已经完美地更改为 image2,非常简单。我只是在寻找第二次更改它的方法。
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
我知道我可以在按钮代码中使用 HTML 更改图像源,但我相信使用 JS 函数会更干净。不过,我对所有解决方案持开放态度。
最佳答案
您需要一个计数器来增加图像数量。只需将 maxCounter
变量设置为您计划使用的最高图像编号。
另外,请注意,此代码删除了内联 HTML 事件处理程序,这是一种将 HTML 连接到 JavaScript 的非常过时的方法。不建议这样做,因为它实际上会围绕回调代码创建一个全局包装函数,并且不遵循 W3C DOM Level 2 事件处理标准。它也不遵循 Web 开发的“关注点分离”方法。最好使用 .addEventListener
将 DOM 元素连接到事件。
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
关于JavaScript/html : Second onclick attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40549606/