本文介绍了如何在IE6中向对象添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AJAX时遇到了一个特别棘手的问题,它在IE7和Firefox中运行良好,但在IE6中没有。

I've got a particularly tricky problem using AJAX, which works fine in IE7 and Firefox, but not in IE6.

我有一个非常简单的本土AJAX框架,它要求我通过添加几个属性来扩展XMLHttpRequest对象(或者在IE的情况下,XMLHttpRequest ActiveXObject)。代码的相关部分如下:

I have a very simple home-grown AJAX framework, which requires that I extend the XMLHttpRequest object (or in the case of IE, the XMLHttpRequest ActiveXObject) by adding a couple of properties. Relevant section of code is as follows:

//the following is the constructor for our ajax request object - which extends the standard object. It is used in the method below it   
function FD_XMLHttpRequest() {     
  var xmlHttpReq = false;
  if (window.XMLHttpRequest) { // Mozilla/Safari
    xmlHttpReq = new XMLHttpRequest();
  } else if (window.ActiveXObject) { // IE
    xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  //we now have the request object - extend it with things we might need to store with it
  xmlHttpReq.onReturnFunc = null; //******ERROR IN IE6******
  xmlHttpReq.targetDivId = null;  //******ERROR IN IE6******
  return xmlHttpReq;  
} 
//To use:
myXHReq = new FD_XMLHttpRequest();
myXHReq.onReturnFunc = someFunction; 
myXHReq.targetDivId = "myDiv";  

问题似乎是FF和IE7允许以这种方式扩展对象,但是IE6没有(它抱怨对象不支持此属性或方法)。我已经尝试过使用prototype属性和各种真正继承的方法,但我无法理解IE6的内容

The problem seems to be that FF and IE7 allow extending an object in this way, but IE6 does not (it complains that "Object doesn't support this property or method"). I've tried using the "prototype" property and various methods of "real" inheritance, but I can't quite get my head around what is going on with IE6

推荐答案

在IE7上,您将获得一个本机JavaScriptXMLHttpRequest对象。与所有JavaScript对象一样,您可以毫无问题地向它们添加任意属性 - 虽然它并不总是一个好主意,因为如果未来的浏览器添加了一个真正的'onReturnFunc'成员,那么您就会混淆它。

On IE7 you are getting a ‘native JavaScript’ XMLHttpRequest object. As with all JavaScript objects you can add arbitrary properties to them without problem — although it's not always a good idea, because if a future browser added a real ‘onReturnFunc’ member of its own you'd then confuse it.

在IE6或IE7上,当禁用native XMLHttpRequest选项时,您将回退到使用原始的ActiveX XMLHttpRequest。但是,ActiveX对象与JavaScript对象的行为完全不同,其中一个区别是您无法添加任意属性。

On IE6, or IE7 when the ‘native XMLHttpRequest’ option is disabled, you fall back to using the original ActiveX XMLHttpRequest. However, ActiveX objects have quite different behaviour to JavaScript objects and one of the differences is you can't add arbitrary properties.

通常,您应该拥有自己的包装类保存您需要的任何额外数据,并保存对真正的XMLHttpRequest对象的引用。

Generally, you should have your own wrapper class that holds any extra data you need, and which holds a reference to the ‘real’ XMLHttpRequest object.

这篇关于如何在IE6中向对象添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 14:45