1

JS を使用して電卓 Web アプリケーションを作成しようとしていますが、いくつかの問題が発生しています。他の開いているスレッドを見て、そのコードを試しましたが、うまくいかないようでした。現在、押されたボタンのIDをログに記録しようとしていますが、ボタンを押すとすべて"undefined"返されます。これが私のコードです:

<html>
<head>
<title>Calculator</title>
</head>

<body>

<p id="text">
<table border="0" id="table">
  <tr>
  <td><input type="button" id="one" value="1" onClick="calculate();"></td>
  <td><input type="button" id="two" value="2" onClick="calculate();"></td>
  <td><input type="button" id="three" value="3" onClick="calculate();"></td>
  </tr>

  <tr>
  <td><input type="button" id="four" value="4" onClick="calculate();"></td>
  <td><input type="button" id="five" value="5" onClick="calculate();"></td>
  <td><input type="button" id="six" value="6" onClick="calculate();"></td>
  </tr>

  <tr>
  <td><input type="button" id="seven" value="7" onClick="calculate();"></td>
  <td><input type="button" id="eight" value="8" onClick="calculate();"></td>
  <td><input type="button" id="nine" value= "9" onClick="calculate();"></td>
  </tr>

  <tr>
    <td> </td>
    <td><input type="button" id="zero" value="0" onClick="calculate();"></td>
  </tr>

</table>




<script>
function calculate(){
console.log(this.id);
}


</script>

</body>
</html>
4

5 に答える 5

5

このようにしてみてください:

function calculate(){
   var e = window.event,
       btn = e.target || e.srcElement;
   alert(btn.id);
}

ライブデモ

説明:

window.eventは、最後に発生したイベントに関する情報を保持します。あなたの場合、それは'click'イベントです。DOM Elementクリックされている をオブジェクトからevent取得できます。targetorsrcElementプロパティ (ブラウザの種類によって異なります) は、それを表しDOM Elementます。

于 2012-07-12T14:39:35.113 に答える
2
<script type="text/javascript">
    function calc(e) {
        console.log(e.id);
    }
</script>

<input type="button" id="btn" onclick="calc(this)" />

独学にもっと多くの努力を払う必要があります:-) 努力しない限り、知識は得られません。

于 2012-07-12T14:40:34.207 に答える
1

要素を取得するために使用できますevent.target

<input type="button" id="one" value="1" onclick="calculate(event);">
<script>
function calculate(event) {
  console.log(event.target.id);
}
</script>
于 2012-07-12T14:38:16.840 に答える
0

上記のようにハードに書き込んでいる場合は、id 値をパラメータとして関数に渡すことができます。

onClick="calculate(one)";
onClick="calculate(two)";
onClick="calculate(three)";

等...

それはそれほど効率的ではありませんが、あなたの場合にはうまくいくはずです。次に、関数は次のようになります。

function calculate(number){
alert(number);
}
于 2012-07-12T14:34:44.267 に答える
0

それは簡単です

onclick=alert(this.id)

または、あなたの場合:

onclick=calculate()

脚本:

function calculate(){
  alert(this.id)
  //this.id - hold the value of the id of the button just click
}
于 2012-07-12T14:35:50.207 に答える