1 Event Proxy: When we need to add events to many elements, we can trigger the handler by adding events to their parent node and delegating the event to the parent node.
For example: Click the button to delete the corresponding entry.
If you add an event to each button, it is tedious to use the event proxy.
The event broker is a browser-based event bubbling mechanism.
Here is the corresponding code:
1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Title</title>6 <style>7 Button{8 Margin-left:50px;9 }Ten Li{ One width:300px; A } - </style> - </Head> the <Body> - <ulID= "Parent-list"> - <LiID= "Post-1">Item 1<ButtonID= "BTN1">Delete</Button></Li> - <LiID= "Post-2">Item 2<ButtonID= "BTN2">Delete</Button></Li> + <LiID= "Post-3">Item 3<ButtonID= "Btn3">Delete</Button></Li> - <LiID= "Post-4">Item 4<ButtonID= "Btn4">Delete</Button></Li> + <LiID= "Post-5">Item 5<ButtonID= "Btn5">Delete</Button></Li> A <LiID= "Post-6">Item 6<ButtonID= "Btn6">Delete</Button></Li> at </ul> - <Script> - //take advantage of the event broker mechanism to get the item that is currently the first number - //Gets the parent node and adds a click event to it - varul=document.getElementById ("parent-list"); - Ul.addeventlistener ("Click",function(e) { in //Check if event source E.targe is Li - if(E.target&&e.target.nodename.tolowercase ()== "Li") { to //Print the current click is the first few item + Console.log ("List Item", E.target.id.replace ("post-",""),"was clicked!"); - } the }); * //The event agent mechanism is used to remove the corresponding Li $ Ul.addeventlistener ("Click",function(e) {Panax Notoginseng if(E.target&&e.target.nodename.tolowercase ()== "Button"){ - ul.removechild (E.target.parentnode) the } + }); A </Script> the </Body> + </HTML>
The simplest understanding of the JS event proxy (event delegate)