Browser-compatible JS notation summary _javascript Skills

Source: Internet
Author: User
Tags eval xpath xslt

First, element lookup problem
1. Document.all[name]
(1) Existing problem: Firefox does not support Document.all[name]
(2) Workaround: Use Getelementsbyname (name), getElementById (ID), etc. to replace.

2. Collection Class object problem
(1) Existing problem: IE in many collection class objects can be used (), but in Firefox can only use [].
For example: IE can use Document.forms ("FormName") to return the name "FormName" form, but in Firefox does not work.
(2) Workaround: Use [], the example can be changed to document.forms["FormName"]

3. HTML element ID is visible in javascript
(1) Existing problem: The ID in the HTML element in IE can be used directly as the subordinate object variable name of document. Not in Firefox.
(2) Workaround: Use getElementById ("Idname") instead of Idname as an object variable.

4. Eval (idname) acquisition of objects
(1) Existing problem: in IE, the use of eval (idname) can get the HTML object ID idname, in Firefox can not.
(2) Workaround: Replace eval (idname) with getElementById (Idname).

5. The variable name is the same as an HTML object ID
(1) Existing problem: In Firefox, because the object ID is not the name of the HTML object, you can use the same variable name as the HTML object ID, ie cannot.
(2) Solution: When declaring variables, all add Var, in order to avoid ambiguity, so that in IE can also be normal operation. In addition, it is best not to take variable names that are the same as the HTML object IDs to reduce errors.

Note: 3, 4 and 5 all belong to the same class of problems.

6. Frame
(1) Existing problems: in IE can be used window.top.frameId and window.top.frameName to get the frame represented by the Window,firefox can only use Window.top.frameName.
(2) Workaround: Set the ID and name of the frame to the same, using Window.top.frameName to access the frame.

Second, Dom operation
1. Sets the textual content of the element.
(1) Existing problem: IE uses innertext, while Firefox uses textcontent to set element text content.
(2) Workaround: If the text content does not contain special characters such as "<" and ">", you can use innerHTML. Otherwise, you can use:

   var child = Elem.firstchild;
      if (child!= null) elem.removechild (child);
      Elem.appendchild (content) (document.createTextNode);

2. Parentelement,parent.children
(1) Existing problems: IE can use parentelement to obtain the parent node, Parent.children get the node of all children node. Firefox is not supported.
(2) Workaround: Use ParentNode and Parent.childnodes.

3. Explanation of the childnodes.
(1) Existing problems: IE and Firefox childnodes interpretation of the different, IE will not contain a blank text node, and Firefox will contain.
(2) Workaround: Use ChildNodes to filter text nodes as follows:

   var children = Elem.childnodes;
     for (i = 0; i < children.length i++) {
      if (Children[i].nodetype!= 3) {//Filter text node
       //...
      }
     }

4. Explanation of the document.getelementsbyname.
(1) Existing problem: IE in getelementsbyname will only check <input> and elements, and in Firefox will check all elements.
(2) Workaround: Do not use getelementsbyname to check for elements other than <input> and , if you want to get a single element, use getElementById as much as possible.

5. Explanation of the document.getElementById.
(1) Existing problem: in IE, getElementById not only checks the id attribute, but also checks the Name property, which is also returned when the Name property matches the parameter. In Firefox, the id attribute is checked only.
(2) Workaround: Try to keep the ID and name the same, and do not allow an element name property to be the same as the id attribute of another element.

III. Events
1. Event.x and EVENT.Y problems
(1) Existing problems: in IE, the event object has x,y attributes, Firefox does not.
(2) Solution: In Firefox, and Event.x is equivalent to Event.pagex. You can use:
MX = Event.x? Event.x:event.pagex;

2. window.event
(1) Existing problem: the use of window.event can not run on Firefox
(2) Solution:
Original code (can run in IE):

   <input type= "button" Name= "Somebutton" value= "Submit" onclick= "Javascript:gotosubmit ()"/>
      ...
      <script language= "javascript" >
        function Gotosubmit () {
          ...
          alert (window.event);  Use window.event ...
        }
      </script>

New code (can be run in IE and Firefox):

  <input type= "button" Name= "Somebutton" value= "Submit" onclick= "Javascript:gotosubmit" (event)/>
      ...
      <script language= "javascript" >
        function Gotosubmit (evt) {
          evt = evt? evt: (window.event? window.event:n ULL);
          ...
          alert (evt);       Use evt ...
        }
      </script>

3. Attachevent and AddEventListener
(1) Existing problems: IE in the use of attachevent to add events, Firefox use AddEventListener.
(2) Solution: as follows, note the difference between the event parameters, one is click, one is onclick.
if (document.attachevent) document.attachevent ("click", Clickhandler,false);
else Document.addeventlistener ("onclick", ClickHandler);

Four, grammar
1. Const
(1) Existing problem: The Const keyword cannot be used in IE. such as const CONSTVAR = 32; This is a syntax error in IE.
(2) Workaround: Do not use const, VAR instead.

2. Extra comma
(1) Existing problems: Firefox object literal constants allow redundant commas, in IE not allowed. The following statement is illegal in IE.
var obj = {' key ': ' AAA ',}
(2) Workaround: Remove the extra comma.

Five, XML
1. Create XMLHttpRequest
(1) Existing problem: Firefox uses Xmlhttprequest,ie to use ActiveXObject.
(2) Solution:

  if (window. XMLHttpRequest) {
     req = new XMLHttpRequest ();
   } else if (window. ActiveXObject) {
     req = new ActiveXObject ("Microsoft.XMLHTTP");
   }

2. Create Dom
(1) Existing problems: Firefox and IE create Dom in different ways.
(2) Solution:

 function Createxmldom () {
     var oxmldom;
     if (window.activexobject) {//IE
      oxmldom = new ActiveXObject ("Microsoft.XMLDOM");
     } else {//Firefox
      oXML Dom = Document.implementation.createDocument ("", "", null);
     }
    }

3. Load XML
  (1) Existing problem: If you want to load external files ie and Firefox can be used:
          oxmldom.async=false;     //This is a must in Firefox
           oxmldom.load ("Test.xml");
     but they load XML strings differently, ie can directly use Oxmldom.loadxml ("<root><child/></root > "), and Firefox wants to use Domparser:
        var oparser = new Domparser ();
           var oxmldom = oparser.parsefromstring ("<root/>", "Text/xml") ;
  (2) Workaround: A better approach is to add a Loadxml method to the xmldom generated by Firefox:
        if ( Isfirefox) {//requires a browser to detect    

    Document.prototype.loadXML = function (sXml) {
      var oparser = new Domparser ();
      var oxmldom = oparser.parsefromstring (sXml, "Text/xml");
      
      while (This.firstchild) this.removechild (this.firstchild);
      
      for (var i = 0; i < oXmlDom.childNodes.length i++) {
       var onewnode = This.importnode (oxmldom.childnodes[i), true); C6/>this.appendchild (Onewnode);}}
    

This allows the Loadxml method to be invoked on IE and Firefox.

4. XPath support
(1) Existing problems: IE can directly use xmldom selectnodes to select nodes according to XPath expression, Firefox is more complex, need to use Xpathevaluator.
Ie:

  var lstnodes = oXmlDom.documentElement.selectNodes ("Employee/name");
    for (var i = 0; i < lstnodes.length i++) {
     alert (lstnodes[i].firstchild.nodevalue);
    }

Firefox:

  var oevaluator = new Xpathevaluator ();
     var oresult = oevaluator.evaluate ("Employee/name", oxmldom.documentelement, NULL, XPATHRESULT.ORDERED_NODE_ITERATOR_ TYPE, null);
     var oelement = Oresult.iteratenext ();
     while (oelement) {
      alert (oElement.firstChild.nodeValue);
      Oelement = Oresult.iteratenext ();
     }

(2) Solution: A better way to add a selectnodes method to the Firefox element.

 if (Isfirefox) {//requires a browser to detect
      Element.prototype.selectNodes = function (sxpath) {
      var oevaluator = new Xpathevaluato R ();
       var oresult = oevaluator.evaluate (Sxpath, this, NULL, xpathresult.ordered_node_iterator_type, NULL);
       
       var anodes = new Array ();
       
       if (Oresult!= null) {
        var oelement = Oresult.iteratenext ();
        while (oelement) {
         anodes.push (oelement);
         Oelement = Oresult.iteratenext ();
        }
       }
       Return anodes
      }
   }

In this way, both IE and Firefox can call the SelectNodes method.

5. XSLT support
(1) Existing problem: IE can use xmldom Transfernode method to convert it to HTML, and Firefox needs to use Xsltprocessor.
Ie:

  Oxmldom.load ("Employee.xml");
    Oxsldom.load ("Employee.xslt");
    var sresult=oxmldom.transformnode (oxsldom);

Firefox:

  var oprocessor = new Xsltprocessor ();
    Oprocessor.importstylesheet (oxsldom);
    var oresultdom = oprocessor.transformtodocument (oxmldom);    
    var oserializer = new XMLSerializer ();
    var sXml = oserializer.serializetostring (Oresultdom, "Text/xml");
    alert (SXML);

(2) Solution: A better way to add a Transfernode method to the Firefox node.

 if (Isfirefox) {//requires a browser to detect
     Node.prototype.transformNode = function (oxsldom) {
     var oprocessor = new Xsltprocessor ();
      Oprocessor.importstylesheet (oxsldom);
      var oresultdom = oprocessor.transformtodocument (oxmldom);
      
      var oserializer = new XMLSerializer ();
      var sXml = oserializer.serializetostring (Oresultdom, "Text/xml");
      
      Return sXml
     }
    }

In this way, both IE and Firefox can call the Transfernode method.

The above is for browser-compatible JS writing summary, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.