2012-07-12 65 views
1

我正在嘗試使用JS創建一個計算器webapp,並且遇到了一些問題。我查看了其他開放的線程並嘗試了該代碼,但它似乎沒有工作。我目前只是試圖記錄被按下的按鈕的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> 
+0

[谷歌?](http://stackoverflow.com/questions/4825295/javascript-onclick-get-the-id-of-the-button-clicked) – danielQ 2012-07-12 14:35:36

回答

5

嘗試這樣的:

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

Live demo

說明:

window.event持有約最後發生的事件的信息。在你的情況下,它是'click'事件。您可以從event對象中檢索正在單擊的DOM ElementtargetsrcElement屬性(取決於瀏覽器的類型)表示DOM Element

+0

謝謝!這很好。你有什麼機會可以對這兩行的內容做一點解釋? var e = window.event, btn = e.target || e.srcElement; – 2012-07-12 14:48:46

+0

@KyleSmith請參閱解釋部分。 – Engineer 2012-07-12 14:54:33

0

如果您的硬盤在寫他們,因爲它似乎你是上面,你可以只值作爲參數的ID傳遞給函數

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

等等

這不是很糟糕的效率,但應該爲你的情況。然後你的函數可以是這樣的:

function calculate(number){ 
alert(number); 
} 
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 
} 
1

您可以使用event.target得到ele換貨。

<input type="button" id="one" value="1" onclick="calculate(event);"> 
<script> 
function calculate(event) { 
    console.log(event.target.id); 
} 
</script> 
2
<script type="text/javascript"> 
    function calc(e) { 
     console.log(e.id); 
    } 
</script> 

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

你需要投入更多的精力進行自我學習:-)除非做出努力,否則永遠不會獲得知識。

相關問題