Ie中不能动态生成input元素中的name等相关属性
在IE6,IE7中,如果动态生成input元素,是无法为其设置name属性的。当然这bug已经在IE8中被修复,详见这里。由于name属性对表单元素非常重要(在提交表单时,与value属性组成键值对,发送到后台),因此必须留意这个bug。
原本bug代码:
<script type="text/javascript">window.onload = function(){var form = document.createElement("form");var input = document.createElement("input");var root = document.body;input.setAttribute("name", "test");//ie6,7,8创建name属性不稳定。6,7不可以8可以root.appendChild(form);//注意添加顺序,添加顺序错的话,IE会内存泄漏form.appendChild(input);alert(form.elements.test)}</script>
<script type="text/javascript">window.onload = function(){var body = document.body;var form = document.createElement("form");form.innerHTML = "<input name='test' type='text' />"body.appendChild(form);alert(form.elements.test)}</script>
<script type="text/javascript">window.onload = function(){var body = document.body;var form = document.createElement("form");try{var input = document.createElement("<input type='text' name='test'>");}catch(e){var input = document.createElement("input");input.setAttribute("name", "test")}body.appendChild(form);//注意添加顺序,添加顺序错的话,IE会内存泄漏form.appendChild(input);alert(form.elements.test)}</script>
var IEfix = { acceptcharset: "acceptCharset", accesskey: "accessKey", allowtransparency: "allowTransparency", bgcolor: "bgColor", cellpadding: "cellPadding", cellspacing: "cellSpacing", "class": "className", colspan: "colSpan", defaultchecked: "defaultChecked", defaultselected: "defaultSelected", defaultvalue: "defaultValue", "for": "htmlFor" , frameborder: "frameBorder", hspace: "hSpace", longdesc: "longDesc", maxlength: "maxLength", marginwidth: "marginWidth", marginheight: "marginHeight", noresize: "noResize", noshade: "noShade", readonly: "readOnly", rowspan: "rowSpan", tabindex: "tabIndex", valign: "vAlign", vspace: "vSpace" }
var body = document.body; var form = document.createElement("form"); form.innerHTML = "<input name='test' type='text' />" body.appendChild(form); if(!+"\v1"){ form.elements.test.setAttribute("onfocus", function(){alert(this.name)}); }else{ form.elements.test.setAttribute("onfocus", "alert(this.name)"); }