関数「document.getElementById」にエイリアスを付けるにはどうすればよいですか
ありがとう
var $ = document.getElemenyById.bind( document );
おそらく最も簡単/最短の方法:
function $(id) { return document.getElementById(id); };
これは私が自分のライブラリで使用するものです。DOMはクラスで$あり、関数のショートカット実装であるgetElementById関数です:
function DOM()
{
this.$ = function(elementIDs)
{
var el;
// If an array of element names is passed.
if (arguments.length > 1)
{
var elements = [];
var length = arguments.length;
for (var i = 0; i < length; i++)
{
// Call this function recursively for each passed parameter.
elements.push(this.$(arguments[i]));
}
return elements;
}
// If a single element name is passed.
if (typeof(elementIDs) == "string")
{
el = document.getElementById(elementIDs);
}
return el;
}
}
使用法:
var el = new DOM().$("elementID");
トップレベルのウィンドウ要素にエイリアスできます。
facebook の connect-jsは、src/core/prelude.jsで次のことを行います。
if (!window.FB) {
FB = {
// ...
$: function(id) {
return document.getElementById(id);
}
// ...
}
}
次に、それを使用するために、次のことを行います。
FB.$('name-of-id');
初期ブロックは、グローバル オブジェクト FB を作成します。このオブジェクト FB を名前空間として使用し、その中にすべてのオブジェクト、プロパティ、および関数を定義します。そうすれば、他のコードがグローバル オブジェクト FB を使用しない限り、他の JavaScript コードで動作します。
function $( s ) {
return document.getElementById( s ) ? document.getElementById( s ) : "";
}
$( "myId" );
これは、ID を取得するためにドル関数 (セレクター) のみを使用することを前提としています。私はそれをテストしませんでしたが、うまくいくはずです。
前回 jQuery のコアを見たとき、引数として文字列を取り、正規表現を使用してそれがどのようなセレクターであるかを判断していました。
$() 関数を見たとき、それはおそらく jQuery や Prototype などのライブラリでした。$ 関数は document.getElementById のエイリアスではなく、関数の機能を拡張するラッパーです。
独自のラッパーを作成するには、関数「エイリアス」を記述できます。
var alias = document.getElemenyById;
また
function alias(id) { return document.getElementById(id); }
しかし実際には、jQuery や Prototype などの利用可能なライブラリの 1 つを使用します。