Internet Explorer JavaScript中的技巧

时间:2014-05-27 19:47:50

标签: javascript internet-explorer

我在此event libray中找到了一个IE修复程序,但除了一个注释外没有任何评论:'即修复';

这段代码有什么作用?对于哪个,即需要这个修复?

 if (elem.setInterval && ( elem != window && !elem.frameElement ) ) {

  elem = window;

}

http://javascript.ru/files/event/event.js

1 个答案:

答案 0 :(得分:4)

好吧,我会解释发生了什么 - 但它有点不稳定。

  // This is a cheap duck test.  normally, only a "top level" object would contain
  // a setInterval property/method
  // By top level, that pretty much means a window, a frame, or an iframe.
  // So this is a lame/broken test for that.
  if (elem.setInterval

  && 

  // Then we check to see if we have a window or a frame.
  ( elem != window && !elem.frameElement ) ) {
    // If we don't have either, assume that we were passed something totally bogus
    // and assign this to the window value.
    elem = window;
  }

在没有阅读API的情况下,我确实查看了代码。一种远远好得多的写作方式将更接近:

add: function(elem, type, handler) {
  if (elem === undefined) {
    elem = window;
  }

或者,正如我写的那样:

add: function(elem, type, handler) {
  // MUCH better test is shown here:
  // http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object

  if (elem === undefined) {
    throw "Event.Add warning. Must pass an element to bind the event to."
  }