使用javascript按下时更改按钮的图像

时间:2017-04-23 15:35:11

标签: javascript

我正在尝试在按下特定按钮时在变量中设置值。当我再次加载页面时,我希望此按钮处于按下状态。我试图在pageloaded函数中检查变量的值,但我不知道如何在javascript中更改按钮的状态。请帮忙

2 个答案:

答案 0 :(得分:0)

<强> HTML:

<button onclick="changeit()"><img src="bla.jpg" id="changevalue"></button>

<强> JS:

function changeit(){

    document.getElementById("changevalue").src = "newimg.jpg";

}

答案 1 :(得分:0)

<强> HTML:

<button id="myButton"><img src="myImage.jpg" id="myImage"></button>

<强> JS:

var NEW_IMAGE_URI = "myNewImage.jpg";
var buttonState = false;

function changeButtonImage(){
   if (buttonState) {
    return;
   }
   document.querySelector("#myImage").src = NEW_IMAGE_URI;
   buttonState = true; 
}

document.addEventListener("DOMContentLoaded", function(event) {
    var buttonElement = document.querySelector('#myButton');
    buttonElement.addEventListener('click',changeButtonImage); 
});