understanding dom0 event model of javascript

荒凉一梦 提交于 2019-12-25 08:49:29

问题


I am trying to express what I understood from reading some articles about dom0 event model in javascript.If there is a mistake in it ,please correct me.

In dom0 model,an event handler can be attached to an element .Only one handler can be attached.When the event occurs,the browser calls that event handler.

There are two ways of doing this

1.Inline model

The handler is added as an attribute of the element.For example a link element (ie <a>) has an attribute called onclick.We add a function hello like this

<a href="#" onclick="hello();"> say hello </a>
...
<script type="text/javascript">
   function hello(){
      window.alert("Hello");
   }
</script>

The problem with this model is that it is intrusive ,since the hello() is put in the body of the element.

2.traditional model

Instead of adding event handler as attribute of element in the body of the element,the adding/removing of handler is done by script.The handler is assigned to the element's property as below

<a href="#" id="hellolink">  say hello </a>
...
<script type="text/javascript">
    function hello(){
        window.alert("Hello");
    }
    //adding handler
    document.getElementById('hellolink').onclick=hello;
</script>

回答1:


Seems about right.

You might want to read: http://www.cross-browser.com/talk/event_interface_soup.php http://en.wikipedia.org/wiki/DOM_events#Traditional_model

and for the code in the traditional model you should have a a window.onload event

so

window.onload = function () {

    var el = document.getElementById('hellolink');
    if (el) {
        el.onclick = hello;
    }
};

depending on what browser you are using function hello might receive the element object, so maybe it'll easier for you if you use something like jQuery to handle your dom events.

http://api.jquery.com/click/



来源:https://stackoverflow.com/questions/10510755/understanding-dom0-event-model-of-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!