一.向表中追加行
完美的做法是:在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” );
}