问题
I try to make a calculator with javascript with the onclick event I want the value of the button to convert an input text box. When I write the code the value of the button briefly in the text box , but it disappears instantly.
The code that i use can you find below this text, what am i doing wrong.
HTML:
var iGetal = 0;
function GetalRekenmachine()
{
iGetal = iGetal + 1;
document.getElementById("Display").value = iGetal;
}
<button id="Cijfer7" value="7" onclick="GetalRekenmachine()">7</button>
<input type="text" id="Display"/>
回答1:
Because the default type of a button is submit. So either cancel the click action or set the type to be button.
<button id="Cijfer7" value="7" onclick="GetalRekenmachine(); return false;">7</button>
or
<button type="button" id="Cijfer7" value="7" onclick="GetalRekenmachine()">7</button>
回答2:
var iGetal = 0;
function GetalRekenmachine(event)
{
iGetal = iGetal + 1;
document.getElementById("Display").value = iGetal;
event.preventDefault()
}
<button id="Cijfer7" value="7" onclick="GetalRekenmachine()">7</button>
<input type="text" id="Display"/>
来源:https://stackoverflow.com/questions/35988724/value-disappears-after-click-event