Several ways to bind native Js events

In Js, there are three commonly used methods of binding events:

1. Direct binding in the Dom element

<button onclick="handleClick">Click Me</button>

2. Binding in JS code

document.getElementById("demo").onclick=function(){
    / * Function body * /     
}

Three. Binding event listener function

Another way to bind events is to use addEventListener () or attachEvent () to bind event listener functions

elementObject.addEventListener(eventName, handle, useCapture);

The event name here has no "on" prefix, handle event handler function, useCapture, boolean, whether to use the capture type, generally false, that is bubbling

elementObject.attachEvent (eventName, handle) The event name here is prefixed with "on".

addEventListener () is a standard method of binding event listener functions, which is supported by W3C, and supported by Chrome, FireFox, Opera, Safari, IE9.0 and above; This method is compatible with attachEvent ().

function addEvent(obj, type, handle){
            try{
                // Chrome、FireFox、Opera、Safari、IE9.0及其以上版本
                obj.addEventListener(type, handle, false);
            } catch (e) {
                 try {
                     // IE8.0 and below 
                    obj.attachEvent ("on" + type, handle);
                }catch(e){
                    obj["on" + type] = handle;
                }
            }
        }

 

Guess you like

Origin www.cnblogs.com/jett-woo/p/11833442.html