问题
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?
回答1:
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.
回答2:
Event handler is a function or other chunk of code that is invoked by browser in response to specific event.
Event listener, in the given context, is a higher level abstraction introduced by javascript library (jquery here) and what this library will do for you is creating event handler that would call some code that will go over listeners and call them one by one. So jquery hides from you the logic of maintaining a list of listener functions and calling them.
来源:https://stackoverflow.com/questions/7507373/event-listeners-vs-event-handlers