如何將簡單的onClick事件處理程序添加到畫布元素中?我是一位經(jīng)驗豐富的Java程序員,但我在近十年來第一次研究JavaScript/HTML 5。我完全困惑于什么應該是最簡單的事情。舉個例子,我只想畫一些東西,并在其中添加一個事件處理程序。我肯定我在做些蠢事,但我到處找遍了,沒有任何建議(例如,這個問題的答案:將onclick屬性添加到JavaScript輸入)起作用。我正在使用Firefox 10.0.1。我的代碼如下。您將看到幾行注釋,在每一行的末尾都描述了發(fā)生了什么(或不發(fā)生什么)。這里正確的語法是什么?我要瘋了!<html><body>
<canvas id="myCanvas" width="300" height="150"/>
<script language="JavaScript">
var elem = document.getElementById('myCanvas');
// elem.onClick = alert("hello world"); - displays alert without clicking
// elem.onClick = alert('hello world'); - displays alert without clicking
// elem.onClick = "alert('hello world!')"; - does nothing, even with clicking
// elem.onClick = function() { alert('hello world!'); }; - does nothing
// elem.onClick = function() { alert("hello world!"); }; - does nothing
var context = elem.getContext('2d');
context.fillStyle = '#05EFFF';
context.fillRect(0, 0, 150, 100);
</script></body>
如何將簡單的onClick事件處理程序添加到畫布元素中?
守著星空守著你
2019-07-06 15:36:38