事件侦听器与事件处理程序 [英] event listeners vs. event handlers

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

问题描述


可能重复:

JavaScript事件侦听器与事件处理程序

element.onload与element.addEventListener(load,callbak,false)


我已经阅读了这个问题,但它是仍然不清楚

 < input type =buttononclick =call_function(); /> 

  $(function(){
$(#my_button)。click(function(){
call_function();
});
});
< input type =buttonid =my_button/>

第一个是事件处理程序,第二个是事件侦听器,是吗? / p>

是一种比其他方式更好的方式,为什么?哪一个更好地处理优雅的退化?

解决方案

功能上没有区别。在这两种情况下,当点击给定的按钮元素时,方法 call_function 将被调用。



风格上虽然有很大的区别。后一个例子被许多人认为更强大,因为它允许开发人员将HTML页面中的3个部分分成完全不同的项目。




  • HTML页面:包含页面的数据

  • CSS样式表:确定数据的显示方式

  • Javascript:提供行为



在第二个例子中,这是可能的,因为JavaScript行为是独立于按钮的定义连接起来的。这允许HTML被完全独立于关联的javascript定义。它们可以在单独的文件中,由单独的人编写,大部分是独立的。有一些限制(例如不要更改 id fields),但总体而言它在逻辑上不同的显示之间提供了很大的自由度。


Possible Duplicate:
JavaScript Event Listeners vs Event Handlers
element.onload vs element.addEventListener(“load”,callbak,false)

I've read this question but it's still unclear to what's the difference between

<input type="button" onclick="call_function();" />

And

$(function() {
    $("#my_button").click(function() {
        call_function();
    });
});
<input type="button" id="my_button" />

The first one is an event handler and the second one is an event listener, am I right?

Is one way better than the other and why? Which one is better at handling graceful degradation?

解决方案

Functionally speaking there is no difference. In both cases the method call_function will be invoked when the given button element is clicked.

Stylistically though there is a big difference. The latter example is considered more robust by many because it allows the developer to separate out the 3 parts of at HTML page into completely different items

  • HTML page: Contains the data of the page
  • CSS stylesheet: Determines how the data is displayed
  • Javascript: Provides the behavior

This is possible in the second example because the javascript behavior is hooked up independently of the definition of the button. This allows for the HTML to be defined completely independent of the associated javascript. They can be in separate files, written by separate people and for the most part mutated independently. There are some restrictions (like don't change id fields) but overall it gives a large degree of freedom between the logically different pieces of the display.

这篇关于事件侦听器与事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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