$
$
$
$ F
$ H
$ R
$ W
Try. these
Document. getElementsByClassName
$ Method -- become a Swiss Army knife (Swiss Army knife)
If provided with a string, returns the element in the document with matching ID; otherwise returns the passed element. takes in an arbitrary number of arguments. all elements returned by the function are extended with Prototype DOM extensions.
Copy codeThe Code is as follows:
Function $ (element ){
If (arguments. length> 1 ){
For (var I = 0, elements = [], length = arguments. length; I <length;
I ++)
Elements. push ($ (arguments [I]);
Return elements;
}
If (Object. isString (element ))
Element = document. getElementById (element );
Return Element. extend (element );
}
First, check the length of the passed parameter:
If the length is equal to 1, judge whether the passed parameter is String. If the passed parameter is String, call the getElementById method to obtain the corresponding object, finally, let the returned object inherit all methods of the Element, so that the returned object can directly call various methods defined in the Element object. For example
Copy codeThe Code is as follows:
// Note quite OOP-like...
Element. hide ('itemid ');
// A cleaner feel, thanks to guaranted extension
$ ('Itemid'). hide ();
If the length is greater than 1, call the $ method recursively (elements. push ($ (arguments [I]);), that is, the passed parameter can be a multi-dimensional array:
$ (['A', 'B', ['C', 'D', ['E', 'F']). Of course, the returned object array is used.
If the length is equal to 0, undefined is returned, that is, alert ($ () is called directly ())
Take a closer look at the Object. isString method:
Copy codeThe Code is as follows:
Function isString (object ){
Return getClass (object) = "String ";
}
// ======> GetClass ()
Function getClass (object ){
Return Object. prototype. toString. call (object)
. Match (/^ \ [object \ s (. *) \] $/) [1];
}
It mainly uses the internal method getClass of the Object to determine the type of the returned Object. In getClass, The toString method of the Object is called, and then the regular expression is used to retrieve the string representing the specific Object.
Object. prototype. toString. call ("2222") returns "[object String]" get "String"
Object. prototype. toString. call (2222) returns "[object Number]" get "Number"
Object. prototype. toString. call (/^ $/) Return "[object RegExp]" get "RegExp"
Here, why do we use the toString method of the Object, because if "2222" is called directly ". toString () will return "2222", that is, the Object inherited from the Object will overwrite the toStirng method, so you must call the toString of the Object here.