Javascript代碼在瀏覽器IE和Firefox相容性的16個問題

來源:互聯網
上載者:User

以下以 IE 代替 Internet Explorer,以 MF 代替 Mozzila Firefox

1. document.form.item 問題

(1)現有問題:

現有代碼中存在許多 document.formName.item("itemName") 這樣的語句,不能在 MF 下運行

(2)解決方案:

改用 document.formName.elements["elementName"]

(3)其它

參見 2

2. 集合類對象問題

(1)現有問題:

現有代碼中許多集合類對象取用時使用 (),IE 能接受,MF 不能。

(2)解決方案:

改用 [] 作為下標運算。如:document.forms("formName") 改為 document.forms["formName"]。

又如:document.getElementsByName("inputName")(1) 改為 document.getElementsByName("inputName")[1]

(3)其它

3. window.event

(1)現有問題:

使用 window.event 無法在 MF 上運行

(2)解決方案:

MF 的 event 只能在事件發生的現場使用,此問題暫無法解決。可以這樣變通:

原代碼(可在IE中運行):

      <input type="button" name="someButton" value="提交" onclick="javascript:gotoSubmit()"/>
       ...
       <script language="javascript">
         function gotoSubmit() {
           ...
           alert(window.event);  // use window.event
           ...
         }
       </script>

新代碼(可在IE和MF中運行):

      <input type="button" name="someButton" value="提交" onclick="javascript:gotoSubmit(event)"/>
       ...
       <script language="javascript">
         function gotoSubmit(evt) {
           evt = evt ? evt : (window.event ? window.event : null);
           ...
           alert(evt);       // use evt
           ...
         }
       </script>

此外,如果新代碼中第一行不改,與老代碼一樣的話(即 gotoSubmit 調用沒有給參數),則仍然只能在IE中運行,但不會出錯。所以,這種方案 tpl 部分仍與老代碼相容。

4. HTML 對象的 id 作為對象名的問題

(1)現有問題

在 IE 中,HTML 對象的 ID 可以作為 document 的下屬物件變數名直接使用。在 MF 中不能。

(2)解決方案

用 getElementById("idName") 代替 idName 作為物件變數使用。

5. 用idName字串取得對象的問題

(1)現有問題

在IE中,利用 eval(idName) 可以取得 id 為 idName 的 HTML 對象,在MF 中不能。

(2)解決方案

用 getElementById(idName) 代替 eval(idName)。

6. 變數名與某 HTML 對象 id 相同的問題

(1)現有問題

在 MF 中,因為對象 id 不作為 HTML 對象的名稱,所以可以使用與 HTML 對象 id 相同的變數名,IE 中不能。

(2)解決方案

在聲明變數時,一律加上 var ,以避免歧義,這樣在 IE 中亦可正常運行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.