`

javascript - trick IE form and its expando attribute

阅读更多

there is a known issue that if you have a form with several inupt elements, and those elemnt happens to have specific id or names then the elements becomes the expando attribute of the form element. 

 

e.g.. 

 

 

<body>
<form id="form" action="/">
<input type="text" id="id"/>
<input type="text" name="action"/>
</form>
</body>

 

 in this example, if you do 

 

form.id, then it return the DOM element, and if you do form.action, it returns another input element. 

 

so to work around, this, there is a method which is called getAttributeNode. please see the following code which first check the attribute node then check to see if there there is attribute with that name (the expando is equivalent of getAttribute) 

 

 

/**************************************
*@Name: ieformexpando.js
*@Summary
*  due to some reason, the IE will treat some input element as attribute to the form object  if the nput elements happens to have a specific name or ID
*
*
* <form id="form" action="/">
*  <input type="text" id="id"/>
* <input type="text" name="action"/>
* </form>
***************************************/

function attr(elem, name) {
  if (elem.nodeName.toUpperCase() === "form" && elem.getAttributeNode(name)) {
    return elem.getAttributeNode(name).nodeValue;
  }
  else {
    return elem.getAttribute(name);
  }
}
 

 

 

and below is the code that test the code above.

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- ieformexpando.html -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="../unit.js"></script>
    <script type="text/javascript" src="ieformexpando.js"></script>
    <script type="text/javascript">
      window.onload = function () {
        test("test IE expando ", function () {
          var form = document.getElementById("form");
          // both are 'form' and '/' accordingly
//          alert(attr(form, "id"));
//          alert(attr(form, "action"));
          assert(attr(form, "id") === 'form', "attr return the attribute node rather that the attribute where is faked by the element");
          assert(attr(form, "action") === '/', "attr return the attribute node rather that the attribute where is faked by the element");
        });
      };
    </script>
    <style type="text/css">
      #results li.pass { color:Green }
      #results li.fail { color:red}
    </style>
</head>
<body>
<ul id="results" />
<form id="form" action="/">
<input type="text" id="id"/>
<input type="text" name="action"/>
</form>
</body>
</html>
 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics