- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 273字
- 2021-07-09 19:07:43
The event object
So far, we attached anonymous functions as event handlers. To make our event handlers more generic and useful, we can create named functions and assign them to the events. Consider the following lines:
function handlesClicks(event){ //Handle click event } $("#bigButton").on('click', handlesClicks);
Here, we are passing a named function instead of an anonymous function to the on()
method. Let's shift our focus now to the event
parameter that we pass to the function. jQuery passes an event object with all the event callbacks. An event object contains very useful information about the event being triggered. In cases where we don't want the default behavior of the element to kick in, we can use the preventDefault()
method of the event object. For example, we want to fire an AJAX request instead of a complete form submission or we want to prevent the default location to be opened when a URL anchor is clicked on. In these cases, you may also want to prevent the event from bubbling up the DOM. You can stop the event propagation by calling the stopPropagation()
method of the event object. Consider this example:
$( "#loginform" ).on( "submit", function( event ) { // Prevent the form's default submission. event.preventDefault(); // Prevent event from bubbling up DOM tree, also stops any delegation event.stopPropagation(); });
Apart from the event object, you also get a reference to the DOM object on which the event was fired. This element can be referred by $(this)
. Consider the following example:
$( "a" ).click(function( event ) { var anchor = $( this ); if ( anchor.attr( "href" ).match( "google" ) ) { event.preventDefault(); } });
- Learn ECMAScript(Second Edition)
- Qt 5 and OpenCV 4 Computer Vision Projects
- Mobile Application Development:JavaScript Frameworks
- FreeSWITCH 1.6 Cookbook
- Oracle Database 12c Security Cookbook
- Java程序設計
- AppInventor實踐教程:Android智能應用開發前傳
- Corona SDK Mobile Game Development:Beginner's Guide(Second Edition)
- C專家編程
- OpenCV Android開發實戰
- Mastering ASP.NET Web API
- Elastix Unified Communications Server Cookbook
- Building E-Commerce Solutions with WooCommerce(Second Edition)
- Android Application Programming with OpenCV 3
- WordPress 3.7 Complete(Third Edition)