Thus, in the daily development of the use of consonant writing, and the event method consonant is a special case. If a DOM object is used to bind multiple events to facilitate reading and writing, it is customary to use consonant, but such writing can result in redundancy of time.
1. Event Redundancy: Multiple event methods call the same code multiple times
The following code is the consonant of an event method:
Copy Code code as follows:
JQuery (function ($) {
$ (' <div id= ' livetip ' ></div> '). Hide (). Appendto (' body ');
var tiptitle = ';
$ (' #mytable '). Bind (' MouseOver ', function (event) {
var $link = $ (event.target). Closest (' a ');
if ($link. length) {
var link = $link [0];
Tiptitle = Link.title;
Link.title = ';
$ (' #livetip '). CSS ({
Top:event.pageY + 12,
Left:event.pageX + 12
})
. html (' <div> ' + tiptitle + ' </div><div> ' + link.href + ' </div> ')
. Show ();
};
}. Bind (' Mouseout ', function (event) {
var $link = $ (event.target). Closest (' a ');
if ($link. length) {
$link. attr (' title ', Tiptitle);
$ (' #livetip '). Hide ();
};
}. Bind (' MouseMove ', function (event) {
var $link = $ (event.target). Closest (' a ');
if ($link. length) {
$ (' #livetip '). CSS ({
Top:event.pageY + 12,
Left:event.pageX + 12
});
};
});
});
The same section of code is used repeatedly by the 5|6 line, the 18|19 line, and the 24|25 line to determine whether the event object exists. This is unreasonable in terms of both code efficiency and code file size.
2. Event delegation: Bind multiple events at once, delegating actions based on the event category
To better optimize the code above, you can modify the code with event delegation, with the following modified code:
Copy Code code as follows:
JQuery (function ($) {
var $liveTip = $ (' <div id= ' livetip ' ></div> '). Hide (). Appendto (' body ');
var tiptitle = ';
$ (' #mytable '). Bind (' mouseover mouseout mousemove ', function (event) {
var $link = $ (event.target). Closest (' a ');
if (! $link. length) {return;}
var link = $link [0];
if (Event.type = = ' MouseOver ' | | | event.type = = ' MouseMove ') {
$liveTip. CSS ({
Top:event.pageY + 12,
Left:event.pageX + 12
});
};
if (Event.type = = ' MouseOver ') {
Tiptitle = Link.title;
Link.title = ';
$liveTip. html (' <div> ' + tiptitle + ' </div><div> ' + link.href + ' </div> ')
. Show ();
};
if (Event.type = = ' Mouseout ') {
$liveTip. Hide ();
if (tiptitle) {
Link.title = Tiptitle;
};
};
});
});
This code once binds multiple events to a DOM object to be processed, delegating different processing code within the code by judging the class of the event. This avoids the duplication of code definitions to avoid the effect of time redundancy.
The above two kinds of code after the implementation of the effect is exactly the same, I believe that everyone can see what kind of code execution efficiency more quickly!
Demo Address http://demo.jb51.net/js/event_delegation/index.html
Package Download http://www.jb51.net/jiaoben/28044.html