IE中的事件会冒泡到窗口吗?

时间:2011-11-24 17:07:04

标签: javascript internet-explorer internet-explorer-8

我将一个简单的点击事件绑定到window对象,但是在IE8中没有调用处理程序(适用于Chrome和FF):

$(window).click(function (e) {
  alert('Hello there! I\'m in the window.click hanlder!');
});

为什么会发生这种情况?

1 个答案:

答案 0 :(得分:5)

似乎IE(测试IE8)不会将事件冒泡到window

以下是一个示例(http://jsfiddle.net/SZXrn/8/):

if (window.attachEvent) // IE
{
  window.attachEvent('onclick', function () {
      alert("Yay window obj was clicked! IE");
  });

  document.attachEvent('onclick', function () {
      alert("Yay document obj was clicked! IE");
  });
}
else if (window.addEventListener) // Other
{
  window.addEventListener('click', function () {
      alert("Yay window obj was clicked! Non-IE");
  });

  document.addEventListener('click', function () {
      alert("Yay document obj was clicked! Non-IE");
  });  
}

因此,解决方案是绑定到document而不是window