---
title: "Ie中不能动态生成input元素中的name等相关属性"
author: "maomaozgc"
date: "2010-07-06T16:38:31Z"
tags: ["IE", "jQuery", "浏览器"]
categories: ["Web前端"]
slug: "ie-input-name"
draft: false
lastmod: "2010-07-06T16:39:53Z"
id: 706752
url: "https://guangcai.iteye.com/blog/706752"
---

在IE6,IE7中，如果动态生成input元素，是无法为其设置name属性的。当然这bug已经在IE8中被修复，详见这里。由于name属性对表单元素非常重要（在提交表单时，与value属性组成键值对，发送到后台），因此必须留意这个bug。 原本bug代码： \[code="java"] \[/code] 解决办法有两个，方式一：用innerHTML，（innerHTML火狐与W3C等都兼容） \[code="java"] \[/code] 方式二： 另一个利用IE强大的createElement特征，它能在创建元素的同时，连属性也一起创建。 \[code="java"] \[/code] 注意： setAttribute在设置属性时，有许多属性在IE下与标准浏览器的命名是不一样的，看一下jQuery，发现它也是不全的。许多地雷埋在这里，下面是一个详尽的参照表：上边为标准游览器的，下边是IE的。 \[code="java"] 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" } \[/code] 　　另外，IE不能用setAttribute为dom元素设置onXXX属性，换言之，不能用setAttribute设置事件。 IE要直接赋给一个函数！ \[code="java"] var body = document.body; var form = document.createElement("form"); form.innerHTML = "" body.appendChild(form); if(!+"\\v1"){ form.elements.test.setAttribute("onfocus", function(){alert(this.name)}); }else{ form.elements.test.setAttribute("onfocus", "alert(this.name)"); } \[/code]