一.向表中追加行
完美的做法是:在table元素下建一个tbody的元素,tr元素增加到tbody元素。而不是直接增加到table元素下。
示例: <table id=”myTable”>
<tbody id=”myTableBody”></tbody>
</table>
增加方法:
var cell = document.createElement(“td”).appendChild(document.createTextNode(“foo”));
var row = document.createElement(“tr”).appendChild(cell);
document.getElementById(“myTableBody”).appendChild(row);
二.通过JavaScript设置元素的样式
使用元素的setAttribute方法设置元素的样式。
例如:var spanElement = document.getElementById(“mySpan”);
spanElement.setAttribute(“style”, “font-weight:bold; color:red;”);
这种方法除了IE,其他浏览器都行得通。
针对IE:解决方法是使用元素style对象的cssText属性来设置所需的样式。
var spanElement = document.getElementById(“mySpan”);
spanElement.style.cssText = “font-weight:bold; color:red;”;
这种方法在IE和其他多数浏览器都能工作,除了Opera。
所以要同时使用这两个方法,才能保证在所有的浏览器上都能正常工作。
如:var spanElement = document.getElementById(“mySpan”);
spanElement.setAttribute(“style”, “font-weight:bold; color:red;”);
spanElement.style.cssText = “font-weight:bold; color:red;”;
三. 设置元素的class属性
var element = document.getElementById(“myElement”);
element.setAttribute(“class”, “styleClass”);
这种方法可以在除IE以外的浏览器工作。
针对IE:element.setAttribute(“className”, “styleClass”);
完美的办法是两种都用:
var element = document.getElementById(“myElement”);
element.setAttribute(“class”, “styleClass”);
element.setAttribute(“className”, “styleClass”);
四. 创建输入元素
单行文本框,按钮,复选框,和单选按钮都可以创建为输入元素,只是type属性的值有所不同。选择框和文本区很简单,只需要向document.createElement传递元素的标记select或者textarea。
单行文本框,按钮,复选框和单选按钮稍难一些,有同样的元素名input,只是type属性的值不同。创建这些元素之后,要设置调用元素的setAttribute方法设置type属性的值。
所以要考虑代码执行顺序:
先创建元素-à设置元素属性-à把元素增加到父元素中。
var button = document.createElement(“input”);
button.setAttribute(“type”, “button”);
document.getElementById(“formElement”).appendChild(button);
五.向输入元素增加事件处理程序
标准做法是使用元素的setAttribute方法,以事件名作为属性名,并把函数处理程序作为属性值,示例:
var formElement = document.getElementById(“formElement”);
formElement.setAttribute(“onclick”, “doFoo();”);
这种方法只有IE不能工作。
IE中使用JavaScript设置元素的事件处理程序,必须对元素使用点记法来引用所需的事件处理程序,并把它赋为匿名函数。
示例:
var formElement = document.getElementById(“formElement”);
formElement.onclick = function() { doFoo(); };
幸运的是,这种方法得到了IE和所有浏览器的支持。
六.创建单选钮
除IE外能用的方法:
var radioButton = document.createElement(“input”);
radioButton.setAttribute(“type”, “radio”);
radioButton.setAttribute(“name”, “radioButton” );
radioButton.setAttribute(“value”, “checked” );
在IE中这样创建的单选按钮,能显示出来,但是无法将其选中。
IE中的方法:
var radioButton = document.createElement(“<input type=’radio’ name=’radioButton’ value=’checked’>”);
这个方法与其他浏览器也不兼容。
所以要先检查浏览器类型:
IE能识别出名为uniqueID的document对象的专用属性,名为uniqueID。IE也是唯一能识别这个属性的浏览器。
方法:
if(document.uniqueID){
//Internet Explorer
var radioButton = document.createElement(“<input type=’radio’ name=’radioButton’ value=’checked’>”);
}
else{
//Standards Compliant
var radioButton = document.createElement(“input”);
radioButton.setAttribute(“type”, “radio”);
radioButton.setAttribute(“name”, “radioButton” );
radioButton.setAttribute(“value”, “checked” );
}