要爲HTML元素添加事件處理,可以在javascript代碼中,設置該元素對象的事件屬性.例如處理 documnet 對象上的 onkeydown 事件,在javascript中設置事件屬性的代碼如下:
<html>
<head>
<script type="text/javascript">
function showKeyDown(e)
{
e=(e)?e:window.event;
alert(e.keyCode);
}
function mouseDown()
{
if(event.button==1)
alert('你按了鼠標左鍵');
if(event.button==2)
alert('你按了鼠標右鍵');
}
function init()
{
window.document.οnkeydοwn=showKeyDown;
window.document.οnmοusedοwn=mouseDown;
}
</script>
</head>
<body οnlοad="init()">
</body>
</html>