我有一个非常简单的HTML计算器。我想输入例如2+2
的输入并按回车键以获得相同字段的结果。
<div id="calculator">
<div id='calc-contain'>
<form name="calculator">
<input id='result' type="text" name="answer" />
<br>
<input type="button" value=" 1 " onclick="calculator.answer.value += '1'" />
<input type="button" value=" 2 " onclick="calculator.answer.value += '2'" />
<input type="button" value=" 3 " onclick="calculator.answer.value += '3'" />
<br/>
<input type="button" value=" 4 " onclick="calculator.answer.value += '4'" />
<input type="button" value=" 5 " onclick="calculator.answer.value += '5'" />
<input type="button" value=" 6 " onclick="calculator.answer.value += '6'" />
</br>
<input type="button" value=" 7 " onclick="calculator.answer.value += '7'" />
<input type="button" value=" 8 " onclick="calculator.answer.value += '8'" />
<input type="button" value=" 9 " onclick="calculator.answer.value += '9'" />
</br>
<input type="button" value=" x " onclick="calculator.answer.value += '*'" />
<input type="button" value=" c " onclick="calculator.answer.value = ''" />
<input type="button" value=" 0 " onclick="calculator.answer.value += '0'" />
<input type="button" value=" / " onclick="calculator.answer.value += '/'" />
<input type="button" value=" + " onclick="calculator.answer.value += '+'" />
<input type="button" value=" - " onclick="calculator.answer.value += '-'" />
</br>
<input style='width:97%;' type="button" value=" = " onclick="calculator.answer.value = eval(calculator.answer.value)" />
</form>
</div>
</div>
答案 0 :(得分:-1)
您可以在javascript中使用此功能
以下是您的示例:
<input id="myInput" value="Some text..">
<button id="myBtn" onclick="javascript:alert('Hello World!')">Button</button>
的JavaScript
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
event.preventDefault();
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
document.getElementById("myBtn").click();
}
});
我希望这很有用
答案 1 :(得分:-1)
<html>
<body>
<script>
function submit(button_press) {
var no1=parseInt(document.getElementById("test").value), no2=parseInt(document.getElementById("test2").value);
var ch=button_press.id;
switch(ch){
case 'btn1': document.getElementById("print").innerHTML=(no1+no2);break;
case 'btn2':document.getElementById("print").innerHTML=(no1-no2);break;
case 'btn3': document.getElementById("print").innerHTML=(no1*no2);break;
case 'btn4': document.getElementById("print").innerHTML=(no1/no2);break;
default: document.write("error");
}
}
</script>
<input type="text" id="test" value="" /><br/>
<input type="text" id="test2" value="" /><br/>
<input type="button" id="btn1" onclick="submit(this)" value="+" />
<input type="button" id="btn2" onclick="submit(this)" value="-" />
<input type="button" id="btn3" onclick="submit(this)" value="*" />
<input type="button" id="btn4" onclick="submit(this)" value="/" />
<p id="print"></p>
</body>