当前位置: 首页 > 图文教程 > 网络编程 > Javascript > document.createElement()用法及注意事项

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 document.createElement()用法及注意事项


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 236 ::
收藏到网摘: n/a

查看关于 createElement 的文章

今天处理了一个日期选择器的ie和ff的兼容问题,本来这种情况就很难找错误,找了好久才把错误定位到js中创建元素的方法document.createElement(),这个方法在ie下支持这样创建元素

var inputObj = document.createElement("<input type='text' size='8' style='border:0px;border-bottom:2px solid #c0c0c0;' " readonly >");

但是这样的情况在ff下是不兼容的。
还有就是特别注意input元素的创建:与 input 有关的元素有很多,比如:checkbox、radio、submit、reset...,因此创建 input 是个很特殊的用法。
创建不同的 input 正确的做法是:
<div id="board"></div>

<script type="text/javascript">
<!--
var board = document.getElementById("board");
var e = document.createElement("input");
e.type = "radio"; //紧接着上一行写
var obj = board.appendChild(e);
obj.checked = true;
//如下写法也是正确的:
//e.checked = true;
-->
</script>

针对 input,在 Netscape、Opera 和 Firefox 中 e.type 既可以在 appendChild 之前,也可以在其之后。但在 IE 中 type 属性必须在前,其它属性必须在后。

IE 创建元素,还有一个特点,就是可以连同属性一同创建,比如:var e = document.createElement("<input type='radio' name='r' value='1' />"); 这在其它浏览器中是不行的,所以我们也不支持。

总结:
针对非 input 元素,各浏览器中,既可以把对元素属性的改变写在显示元素(insertBefore 或 appendChild)之前,也可以在其后。
针对 input 元素,为了兼容 IE,type 属性写在显示元素(insertBefore 或 appendChild)之前,其它属性写在其后。

推荐:
除了 input 元素的 type 属性写在显示元素(insertBefore 或 appendChild)之前外,其它属性都写在显示元素之后。
改变属性时,对写在显示元素(insertBefore 或 appendChild)之前的用 createElement 的返回值,对写在显示元素之后的用 insertBefore 或 appendChild 的返回值。