One. Capturing, adding events
Because there are two ways to capture and add events from both the Web and Microsoft, there are multiple events and Cross-browser-compatible implementations that will duplicate the input if ... else ... Statement. A good way to do this is to create a reusable event-handling function, such as:
function catchevent (EVENTOBJ, event, EventHandler) {
if (eventobj.addeventlistener) {//W3C model
Eventobj.addeventlistener (Event,eventhandler,false);
} else if (eventobj.attachevent) {//Microsoft model
event = "on" + event;
Eventobj.attachevent (Event,eventhandler);
}
Two. Cancel an Event
The process of canceling an event can also be written as a reusable function:
function CancelEvent (event) {
if (event.preventdefault) {//W3C model
event.preventdefault ();
Event.stoppropagation ();
} Else{//ie model
Event.returnvalue = false;
Event.cancelbubble = true;
}
}
In a typical example form validation, in the Submit event handle function, you can stop the form submission in the following ways
function Formfunction (evnt) {
var event = evnt? evnt:window.event;
...//Some operations
if (event.preventdefault) {
event.preventdefault ();
Event.stoppropagation ();
} else{
event.returnvalue = false;
Event.cancelbubble = true;
}
}
The Stoppropagation () method blocks event bubbling on browsers that follow the DOM level 2 event-handling mechanism;
Cancelbubble = true; Block event bubbling to IE browser.
The Preventdefault () function is used to block the default behavior based on that element and event;
The Returnvalue=false;returnvalue property is equivalent to returning a value of false in a function.
The consortium model is two methods, and the Microsoft model is two attributes.
Example: Read the following form
You need to detect whether the keyword (input#keywords) is empty before submitting the form, and if it is blank, do not commit.
Use the traditional event bindings method and the "event binding" method to give the event bindings, respectively.
<form method= "Get" action= "index.php" id= "Search-tuan" > Keywords: <input type= "text" value= "xx" id= "keywords" name= "KW" class= "keywords"/> <input type= "Submit" class= "button" value= "submitted"/> <input type= "hidden" value= " Search "Name=" Do "id=" action "/> <input type=" hidden "value=" Beijing "Name=" City "id=" City "/> </form>
window.onload = init; //traditional function init () { document.getElementById (" Search-tuan ") .onsubmit = check; } Function check () { var keyvalue = document.getelementbyid ("keywords") .value; if (! KeyValue) { alert ("value is empty"); return false; } } function Catchevent (Eventobj,event,eventhandler) {//w3c if (EventObj.addEventListener) { eventobj.addeventlistener (Event,eventhandler,false); }else if (eventobj.attachevent) { event = "on" + event; Eventobj.attachevent (Event, EventHandler);