開發跨瀏覽器JavaScript時要注意的問題

來源:互聯網
上載者:User
、          向表中追加行

定義table時使用tbody元素,以保證包括IE在內的所有瀏覽器可用

例:定義如下一個空表

<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);

*IE中需要先建立行,再建立列,再建立內容

2、          設定元素的樣式

Var spanElement = document.getElementById(“mySpan”);

//下面寫法保證出IE外,所有瀏覽器可用

spanElement.setAttribute(“style”,”font-weight:bold;color:red;”);

//下面的寫法保證IE可用

spanElement.style.cssText=”font-weight:bold;color:red;”;

3、          設定元素的class屬性

Var element = document.getElementById(“myElement”);

//下面的寫法保證除IE外,所有瀏覽器可用

Element.setAttribute(“class”,”styleClass”);

//下面寫法保證IE可用

Element.setAttribute(“className”,”styleClass”);

4、          建立輸入元素

Var button = document.createElement(“input”);

//單行文字框、複選框、單選框、單選鈕、按鈕需要此屬性區別

Button.setAttribute(“type”,”button”);

Document.getElementById(“formElement”).appendChild(button);

5、          向輸入元素增加事件處理常式

Var formElement=document.getElementById(“formElement”);

//所有瀏覽器可用

formElement.onclick=function(){doFoo();};

//除IE外,所有瀏覽器可用

formElement.setAttribute(“onclick”,”doFoo();”);

6、          建立單選鈕

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”);

}

7、          insertRow,insertCell,deleteRow

在IE中,table.insertRow()如果沒有指定參數,則在表格後面添加行,預設參數位-1;如果在Firefox中,則一定要加參數,如:insertRow(-1)。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.