DIV CSS 佈局教程網

用 $ 函式簡化 document.getElementById
編輯:JavaScript基礎知識     

在沒有使用 jQuery 或 prototype 的專案中,可以用 $ 函式簡化 document.getElementById 的冗長寫法。

function $(id) {
  return document.getElementById(id);
}

兼容舊瀏覽器

若需要支援更舊的瀏覽器,可以加入多層判斷。

function $(objectId) {
  if (document.getElementById && document.getElementById(objectId)) {
    return document.getElementById(objectId);
  } else if (document.all && document.all(objectId)) {
    return document.all(objectId);
  } else if (document.layers && document.layers[objectId]) {
    return document.layers[objectId];
  } else {
    return false;
  }
}

這個小函式能減少重複程式碼,讓後續開發更簡潔。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved