Home > Article > Web Front-end > Code implementation of javascript event delegation and code optimization
This article brings you the code implementation and code optimization of js event delegation. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Two days ago, I took over a project from a colleague, which is a website homepage. There is a piece of code in it that is very cumbersome. The function to be realized is,
By adding mouse move in and move out events to the parent element, To control the display and hiding of child elements.
html code, there are four parent element divs, each parent element nests a child element div,
This is an interception of one of the divs:
The simplest and crudest method is this:
Directly write eight methods to set the attribute style block or none respectively.
Although it is simple to write like this, we still need to make changes due to code optimization and page response speed.
I asked a colleague and said that looking at the related methods of event delegation can effectively solve this problem.
After some operations, the poster wrote the following code:
Writing like this can achieve the effect, but when checking the console, there is nothing Fluttering red.
It really gives me a headache when I see this. Obviously the effect is achieved, why is it still reporting an error?
During my lunch break today, I lay down and thought about it, and suddenly I got inspiration.
This is the modified code. After reading this, you will understand that this is because target refers to the current object.
When the mouse moves to the parent element div, the p attribute of the child element changes to block and will be displayed.
But when you move to the child element div, the target points to the child element, and the child element does not have firstElementChild, so an error will be reported.
At this time we only need to add a judgment. If the sub-object does not exist, then modify the properties of the current object.
Otherwise, that is, if the sub-object exists, then modify the sub-object properties.
After two days of hard work, I finally optimized such a small piece of code.
Originally I thought of a for loop, but after looping like this, there are still a lot of DOM operations.
Related recommendations:
Comparison of js operator priorities and analysis of js logical operators
The above is the detailed content of Code implementation of javascript event delegation and code optimization. For more information, please follow other related articles on the PHP Chinese website!