Javascript事件冒泡不按预期工作

时间:2010-05-19 13:13:00

标签: javascript javascript-events event-bubbling event-propagation

做一场噩梦试图找出事件Bubbling ..

Full test case

<html> 
<head> 
<script type="text/javascript"> 
function $(ob) { return document.getElementById(ob) }

function bodyClick()
{
  $('win_clicks').value = parseInt($('win_clicks').value) + 1;
}

window.addEventListener('load',function(e)
{
  $('bl_lnk').addEventListener('click',function (e)
  {
    $('bl_lnk_clicks').value = parseInt($('bl_lnk_clicks').value) + 1;
  }, true);

  $('rd_lnk').addEventListener('click',function (e)
  {
    $('rd_lnk_clicks').value = parseInt($('rd_lnk_clicks').value) + 1;
  }, false);

}, false);
</script>
</head>

<body onclick="bodyClick();" style="font:16px Tahoma"> 

<div id="bl_lnk" style="position:absolute; width:250px; top:100px; left:50%; margin-left:-125px; padding:20px; background:#AAFFFF; border:1px solid #55AAFF; text-align:center; cursor:pointer">
  I'm a link, Click me! &nbsp; &nbsp; &nbsp; &nbsp; and me!
</div>

<div id="rd_lnk" style="-moz-border-radius:40px; border-radius:50px; position:absolute; width:60px; height:40px; top:103px; left:50%; margin-left:77px; padding:5px; border:3px solid #FF6666; cursor:pointer"></div> 

<div style="position:absolute; width:250px; top:200px; left:50%; margin-left:-125px; padding:20px; background:#fff6bf; border:1px solid #FFD324;">
  <table cellspacing="10"> 
    <tr>
      <td>Blue Link Clicks:</td>
      <td><input type="text" id="bl_lnk_clicks" value="0" style="width:35px; border:0; background:transparent" /></td>
    </tr>
    <tr>
      <td>Red Link Clicks:</td>
      <td><input type="text" id="rd_lnk_clicks" value="0" style="width:35px; border:0; background:transparent" /></td>
    </tr> 
    <tr>
      <td>Body Clicks:</td>
      <td><input type="text" id="win_clicks" value="0" style="width:35px; border:0; background:transparent" /></td>
    </tr> 
  </table>
</div> 

</body> 
</html> 

根据我的理解点击红色边框内的区域应触发所有3个事件处理程序(红色,蓝色和身体),只触发红色和身体..

我尝试改变addEventListener的第三个值并更改返回值,但没有用,有什么想法吗?

d

1 个答案:

答案 0 :(得分:3)

红色div应该在内部(结构上在HTML中,而不是在视觉上),以便事件传播到蓝色div。