关于JavaScript的事件

     刚刚学习Javascript的事情,我不明白这是什么东西。书中是这样说的,所有事件都以对象存在。但我还是不明白,学习事件到底可以干什么,不要问为什么,没有的一本书会告诉你。(自小教导学习从来没有问有什么用的)不过凭常识可以知道,像click,mouseover这些都是事件。在IE中,事件对象是window对象的一个属性:event。但是标准的DOM中获取事件对象却与IE不同,从各大搜索引擎可以知道。

我做了一个很小的例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head>
    <title>An XHTML 1.0 Strict standard template</title>
    <meta http-equiv="content-type"    content="text/html;charset=gbk" />
    <script type="text/javascript">
     function onClick(e){
      e = e || window.event;//兼容事件
      target = document.getElementById("foo");
      var obj = target.getAttribute('title');
      alert(obj);
     }
     window.onload=function(){
     var d = document.getElementById("foo");
     d.onclick = onClick; //响应的函数
     }
    </script>
</head> 

<body> 

     <div id="foo" title="testing...">Hello,Wolrd!</div> 

</body>
</html>

     这跟平常的有什么不同,它可以完成什么重要工作?在初级阶段,我还是不懂。下面还有一个例子,可以让我觉得怎么像是监听事件。只不过可以判断出事件的类型,难道这就是它的用处?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head>
    <title>An XHTML 1.0 Strict standard template</title>
    <meta http-equiv="content-type"    content="text/html;charset=gbk" />
    <script type="text/javascript">
    function handle(e){
     var oDiv = document.getElementById("foo2");
    e = e || window.event;
     if (e.type == "click") {
        oDiv.innerHTML+="点击了!";
     }else if(e.type == "mouseover"){
        oDiv.innerHTML+="你在我上面移过。";
     }
    }
    window.onload=function(){
      var oDiv = document.getElementById("foo1");
      oDiv.onclick=handle;
      oDiv.onmouseover=handle;
    }
    </script>
</head> 

<body>
<div id="foo1" style="margin:0 auto;width:600px;height:300px;border:1px solid #aaa;text-align:center">鼠标单击和移过</div>
<div id="foo2"></div> 

</body>
</html>
posted @ 2010-09-23 18:00  e.e.p  阅读(290)  评论(0编辑  收藏  举报