'data'为null或不是对象IE8 [英] 'data' is null or not an object IE8

查看:232
本文介绍了'data'为null或不是对象IE8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用postMessage将iframe中的消息传输到其父页面。这是我的代码。
在iframe中:

I am transmitting message from an iframe to its parent page using postMessage. This is my code. In iframe:

$(".history_date").click(function(event) {
  window.top.postMessage($(this).text(), "*");
});

在父页面中:

$(function(){
window.onmessage = function(e){
    if(e.data){
        //do something

    }
};
});

它在chrome,firefox和IE9 / 10中运行良好,但在IE8中,错误不确定

It works well in chrome, firefox and IE9/10, but in IE8, the error indecates


'data'为空或不是对象。

'data' is null or not an object.

如何解决?在此先感谢。

How to fix it? Thanks in advance.

推荐答案

IE8 缺少DOM2事件附件,仍使用全局 event object而不是传递给事件处理程序的对象。你说错误是'data'是null或者不是对象,你确定它不是'e'是null或者不是对象

IE8 still lacks DOM2 event attachment, still using the global event object rather than one it passes into event handlers. You've said the error is 'data' is null or not an object, are you sure it's not 'e' is null or not an object?

如果是,那么这应该解决它:

If it is, then this should fix it:

window.onmessage = function(e){
   e = e || window.event;
   if (e.data) {
       // ...
   }
};

在IE8及更早版本中,没有参数传递给事件处理程序。相反,您查看全局事件变量(全局变量也是窗口对象的属性)。所以在IE8及更早版本中, e 将是 undefined ,而在IE9 +和所有其他浏览器上, e 将成为事件对象。

On IE8 and earlier, no argument is passed into event handlers. Instead, you look at the global event variable (global variables are also properties of the window object). So on IE8 and earlier, e will be undefined, whereas on IE9+ and all other browsers, e will be the event object.

所以这一行:

e = e || window.event;

...使用奇怪强大的 || 运算符,如果该参数为truthy,将返回其第一个参数,或第二个论点,如果第一个是假的。由于 undefined 是假的,在IE8及更早版本中, e = e || window.event window.event 分配给 e 。在IE9 +和所有其他浏览器上,它只是将 e 分配回自身(无操作)。

...uses the curiously-powerful || operator, which will return its first argument if that argument is "truthy," or its second argument if the first is "falsey." Since undefined is falsey, on IE8 and earlier, e = e || window.event assigns window.event to e. On IE9+ and all other browsers, it just assigns e back to itself (a no-op).

这是代码中的常见模式,必须与IE8及更早版本以及将事件对象传递到处理程序的浏览器进行交互。

This is a common pattern in code that has to interact with both IE8 and earlier and browsers that pass the event object into the handler.

这篇关于'data'为null或不是对象IE8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆