我是一名有经验的Java程序员,但第一次接触大约十年前的JavaScript/HTML5。我完全被应该是最简单的事情难住了。
例如,我只想画点东西并在其上添加一个事件处理程序。我确定我正在做一些愚蠢的事情,但我已经搜索了所有建议的内容(例如,这个问题的答案:Add onclick property to input with JavaScript),但没有任何作用。我正在使用Firefox 10.0.1。我的代码如下。您会看到几行注释,在每行的末尾都有一个关于发生什么或不发生什么的描述。
正确的语法是什么?我快疯了!
<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
替代onClick
。 - noob<script>
中调用了alert()
,而不是定义一个将调用alert()
的函数。其余的都没有做任何事情,因为onclick
的大小写不正确。 - LarsH