document.getElementById() 的簡寫技巧

來源:互聯網
上載者:User

在我們寫javascript的時候經肯定會經常用到 document.getElementById() 這個方法,這麼長一串很容易寫錯,而且其中getElementById又有大小寫之分。
 其實prototype.js裡提倡的一個方法就是使用$()簡寫,通過以下的函數,你可以用$('id')來實現document.getElementById('id') 這個功能,怎麼樣,很爽吧!

function $()
{
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++)
  {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    if (arguments.length == 1)
      return element;
    elements.push(element);
  }
  return elements;
}



arguments 屬性

為當前執行的 function 對象返回一個arguments 對象。

function.arguments

function 參數是當前執行函數的名稱,可以省略。

說明

通過 arguments 屬性,函數可以處理可變數量的參數。 arguments 對象的 length
屬性包含了傳遞給函數的參數的數目。對於arguments 對象所包含的單個參數,其存取方法與數組中所包含的參數的存取方法相同。

樣本

下面的例子說明了 arguments 屬性的用法:

function ArgTest(){
   var i, s, numargs = arguments.length;
   s = numargs;
   if (numargs < 2)
      s += " argument was passed to ArgTest. It was ";
   else
      s += " arguments were passed to ArgTest. They were " ;
   for (i = 0; i < numargs; i++)
      {
         s += arguments[i] + " ";
      }
   return(s);
}
相關文章

聯繫我們

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