了解javascript的dom0事件模型 [英] understanding dom0 event model of javascript

查看:64
本文介绍了了解javascript的dom0事件模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过在 javascript 中阅读有关 dom0事件模型的一些文章来表达我的理解。如果有是一个错误,请纠正我。

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.

在dom0模型中,一个事件处理程序可以附加到一个元素。只能附加一个处理程序。当事件发生时,浏览器调用该事件处理程序。

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。内联模型

处理程序作为元素的属性添加。例如链接元素 (即< a> )有一个名为的属性onclick 。我们像这样添加一个函数hello

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>

这个模型的问题是它是侵入性的,因为hello()放在体内元素。

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>


推荐答案

似乎是正确的。

您可能需要阅读:
http:/ /www.cross-browser.com/talk/event_interface_soup.php
http://en.wikipedia.org/wiki/DOM_events#Traditional_model

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

对于传统模型中的代码,你应该有一个window.onload事件

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

所以

window.onload = function () {

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

取决于您使用的是什么浏览器函数hello可能会收到元素对象,所以也许它会更容易如果你使用像jQuery这样的东西来处理你的dom事件,你就可以了。

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/

这篇关于了解javascript的dom0事件模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆