Jquery already provides various event handling methods. Instead of Directly Writing events on html elements, we can directly add events to objects obtained through jquery.
For example:
$ ("# Msg"). click (function () {alert ("good")}) // added a click event for the element
$ ("P "). click (function (I) {this. style. color = ['# f00',' #0f0 ',' # 00f'] [I]})
// Set different processing for three p-element click events
Several custom events in jQuery:
(1) hover (fn1, fn2): a method that imitates a hover event (move the mouse over an object and remove it. When you move the cursor over a matching element, the specified first function is triggered. When you move the cursor out of this element, the specified second function is triggered.
// When you place the cursor over a row of the table, set the class to over and the class to out when you leave the table.
$ ("Tr"). hover (function (){
$ (This). addClass ("over ");
},
Function (){
$ (This). addClass ("out ");
});
(2) ready (fn): binds a function to be executed when the DOM is loaded and can be queried and manipulated.
$ (Document). ready (function () {alert ("Load
Success ")})
// After the page is loaded, the system prompts "Load ".
"Success", unlike the onload event, onload requires the page content to be loaded (images, etc.), and ready is triggered when the html code of the page is downloaded. Equivalent to $ (fn)
(3) toggle (evenFn, oddFn ):
Switch the function to be called each time you click. If a matching element is clicked, the specified first function is triggered. When the same element is clicked again, the specified second function is triggered. The subsequent clicks repeatedly call the two functions.
// Add or delete a class named selected every time you click it.
$ ("P"). toggle (function (){
$ (This). addClass ("selected ");
}, Function (){
$ (This). removeClass ("selected ");
});
(4) trigger (eventtype): triggers an event on each matching element.
For example:
$ ("P"). trigger ("click"); // triggers the click event of all p elements
(5) bind (eventtype, fn), unbind (eventtype ):
Event binding and anti-binding
Deletes a bound event from each matching element.
For example:
$ ("P"). bind ("click ",
Function () {alert ($ (this). text ());});
// Add a click event for each p element
$ ("P"). unbind ();
// Delete all events on all p elements
$ ("P"). unbind ("click") // Delete the click Event on all p elements