In general, to understand this code, you need to master the following two functions
One is typeof, and one is the ternary operator.
Read the above article and then look at the following is better to understand
Generally used function code
function $ (ID) {return typeof id=== ' string ' document.getElementById (ID): ID;}
var Getby = function (ID) {return
"string" = = typeof ID? document.getElementById (ID): ID;
function is the same.
The role of this function is to use the ID selector can be abbreviated, as far as the meaning of the judgement is that the incoming parameter is a string to return document.getElementById (ID), the other returns the parameter itself, this is just a page DOM elements of a primitive version of the function, is not perfect yet.
1, this is a section of JavaScript code
$ is an indicator. You can also use GetID and so on, if you use jquery on the page is not recommended to use $, because jquery defaults to use is $
? : Is an operator
Return "string" = = typeof ID? document.getElementById (ID): ID;
Can also be written as
if ("string" = = typeof id) return
document.getElementById (ID);
Else
Some people feel that the above code, why not use {}, because the code is relatively short only one line is not required {}
As shown below
if ("string" = = typeof id) {return
document.getElementById (ID);
}
else {return
ID;
}
Specific can refer to this article: http://www.jb51.net/article/50197.htm
2, the expression of 1? Expression 2: Expression 3
This is a formula; his operation is: first, the expression 1, if true, the expression of the formula 2 of the operation, or the whole equation is the expression of the value of 3 of the operation results, do not understand the friend can refer to this article: http://www.jb51.net/article/64237.htm
In your case, expression 1 is "string" = = typeof ID, function is to determine whether the data type of ID is string, = = is the operator to determine whether equality
Expression 2 is document.getElementById (ID) An HTML element that gets the value of the ID as the parameter ID
Expression 3 is the ID of this variable (in general, this variable is mostly object), if the object is not document.getElementById, can be used directly.
Cloud Habitat Community Original collation, reprint please indicate the source