Home > Web Front-end > JS Tutorial > A brief analysis of the usage and benefits of javascript event delegation_javascript skills

A brief analysis of the usage and benefits of javascript event delegation_javascript skills

WBOY
Release: 2016-05-16 15:06:47
Original
1291 people have browsed it

This article briefly introduces the usage and benefits of JavaScript event delegation for your reference. The specific content is as follows

Event delegation: Using the principle of bubbling, add events to the parent to trigger execution effects,
Benefits: Improved performance, newly added elements will also have previous events.
event object: event source, no matter which event it is in, as long as the element you operate is the event source

Get event source:
IE:window.event.srcElement

Under the standard : event.target target.nodeName to determine which tag

The code is applied as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>

</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
window.onload=function ()
{
  var oUl=document.getElementById('ul1');
  var oBtn=document.getElementById('btn1');
  var iNow=5;
  //事件源的方法依然保留父级事件!
  oUl.onmouseover=function(ev)
  {
    var ev=ev||window.event;
    var target=ev.target||ev.srcElement;
    if(target.nodeName.toLowerCase()=='li')
    {
      target.style.background='red';
    }
  }
  oUl.onmouseout=function(ev)
  {
    var ev=ev||window.event;
    var target=ev.target||ev.srcElement;
    if(target.nodeName.toLowerCase()=='li')
    {
      target.style.background='';
    }
  }
  oBtn.onclick=function()
  {
    iNow++;
    var oLi=document.createElement('li');
    oLi.innerHTML=111*iNow;
    oUl.appendChild(oLi);
  }
}
</script>
</head>
<body >
<input type="button" value="添加" id='btn1'>
<ul id='ul1'>
  <li>11111</li>
  <li>22222</li>
  <li>3333333</li>
  <li>44444444</li>
  <li>66666666</li>
</ul>
</body>
</html>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template