Do events bubble up to window in IE?

家住魔仙堡 提交于 2021-02-19 05:24:08

问题


I'm binding a simple click event to the window object but the handler doesn't get called in IE8 (works on Chrome and FF):

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

Anyone why this is happening?


回答1:


It seems that IE (testing IE8) doesn't bubble events to the window.

Here's an example ( 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");
  });  
}

So, the solution is to bind to the document instead of window.



来源:https://stackoverflow.com/questions/8260507/do-events-bubble-up-to-window-in-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!