事件委派:捕获Element上的事件而不是其子项

时间:2014-10-06 16:16:32

标签: javascript html css

HTML

  <section id='mainwrap'>
  .. 
  ....
  ......
  <section class='innerwrap'>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
  </section>
 .....
 ....
...
</section>

此处 section innerwrap 是在应用程序中动态添加的。我已经委派了一个活动 mainwrap部分(这是静态的)。

问题:部分内部包裹 ........每次 无法 捕捉点击事件点击的元素是它的子div。

JS

&#13;
&#13;
document.getElementById('mainwrap').addEventListener('click',handler,false);

function handler(e){
  event = e || window.event;
  var target = e.target || e.scrElement;
  var cls = target.className;
  
  
  console.log(target,cls);
  if(cls === 'innerwrap'){
   console.log('my right element clicked');
  }
  
}  
  
&#13;
.innerwrap{
  border:2px solid #ddd;
  position:relative;
  z-index:1;
  display:inline-block;
}

.innerwrap > div{
  border:1px solid #efefef;
  position:relative;
  z-index:0;
  display:inline-block;
  margin-right:-4px;
 }
&#13;
  <section id='mainwrap'>
  <section class='innerwrap'>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
    <div>123</div>
  </section>
</section>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

您需要爬上文档树,直到找到正确的元素:

document.getElementById('mainwrap').addEventListener('click',handler,false);

function handler(e){
  e = e || window.event;
  var element = e.target || e.srcElement;

  while (element.className !== "innerwrap" && element !== this) {
    element = element.parentNode;
  }

  if(element.className === 'innerwrap'){
    console.log('my right element clicked');
  }
}

event.target属性始终是点击的最深元素,因此您只需要继续查看parentNode,直到找到合适的元素。

答案 1 :(得分:0)

试试这个:

  if(cls === 'innerwrap'){
        console.log('my right element clicked');
  }else{
     if(target.id === "mainwrap"){
        console.log('Ooops wrong div!');
     }else{
        target.parentNode.click(); 
     }
  }

答案 2 :(得分:-1)

您可以为实际想要接收事件的每个容器添加一个事件处理程序(如果这在您的设置中可行):

(某处:)

(function() {
 var container = document.getElementById('mainwrap');
 container.addEventListener('click',handler,false);

 function handler(e) {
  e = e || window.event;
  var element = e.target || e.srcElement;

  console.log("Element actually clicked: ", element);
  console.log("Container receiving event: ", container);
 }

})();

或者扩展为(可以为多个容器注册处理程序..):

function registerHandlerForContainer(container_id, handler) {
 var container = document.getElementById(container_id);
 container.addEventListener('click',delegating_handler,false);

 function delegating_handler(e) {
  handler(container, e);
 }
}

function handler(container, e) {
  e = e || window.event;
  var element = e.target || e.srcElement;

  console.log("Element actually clicked: ", element);
  console.log("Container receiving event: ", container);
 }

registerHandlerForContainer('mainwrap', handler);