嗯...我想在单击按钮时将按钮的值插入文本输入,但是js为按钮返回'未定义'。看起来我想制作计算器,是的,但制作计算器的第一步是将按钮的值插入文本。
<html>
<head>
<meta charset="utf-8"/>
<title>My Calculator</title>
<style type="text/css">
</style>
<script type="text/javascript">
function action(){
/* This is for testing the function to run
alert('Successful!');*/
var val = document.getElementsByName('num').value;
document.getElementById(/*'result' or 'answer'*/).innerHTML= val;
}
</script>
</head>
<body>
<input id="result" type="text" readonly /><br/>
<button name="num" value="1" onclick="action()">1</button>
<button name="num" value="2" onclick="action()">2</button>
<button name="num" value="3" onclick="action()">3</button>
<button name="operand">+</button><br/>
<button name="num" value="4" onclick="action()">4</button>
<button name="num" value="5" onclick="action()">5</button>
<button name="num" value="6" onclick="action()">6</button>
<button name="operand">-</button><br/>
<button name="num" value="7" onclick="action()">7</button>
<button name="num" value="8" onclick="action()">8</button>
<button name="num" value="9" onclick="action()">9</button>
<button name="operand">*</button><br/>
<button name="operand">C</button>
<button name="num" value="0" onclick="action()">0</button>
<button name="operand">=</button>
<button name="operand">/</button>
<h1 id="answer"></h1>
</body>
答案 0 :(得分:1)
你能尝试这样吗,
HTML
<button name="num" id="9" value="9" onclick="action(9)">9</button>
脚本
function action(id){
/* This is for testing the function to run
alert('id!');*/
var val = document.getElementById(id).value;
document.getElementById('result').value += val;
}
你也在为多个元素使用相同的名称