JavaScript中也使用$貨幣符號來代替document.getElementById

來源:互聯網
上載者:User

複製代碼 代碼如下:function $(id){return document.getElementById(id);

上面的對於新版本的瀏覽器都是沒有問題的,如果使用古老的瀏覽器,可以使用下面的函數複製代碼 代碼如下:function $(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
// W3C DOM
return document.getElementById(objectId);
}
else if (document.all && document.all(objectId)) {
// MSIE 4 DOM
return document.all(objectId);
}
else if (document.layers && document.layers[objectId]) {
// NN 4 DOM.. note: this won't find nested layers
return document.layers[objectId];
}
else {
return false;
}
}

來實現$代替document.getElementById的效果,雖然簡單,但對於沒有引用了prototype和jquery等架構的,避免了每次寫document.getElementById,只需在一個公用JavaScript檔案定義後便可處處使用了。

相關文章

聯繫我們

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