2012-07-12 69 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)" /> 

你需要投入更多的精力进行自我学习:-)除非做出努力,否则永远不会获得知识。

相关问题