JavaScript syntax
In another question answered here I found the following JavaScript code:
function _dom_trackActiveElement(evt) {
if (evt && evt.target) {
document.activeEleme开发者_如何转开发nt = evt.target == document ? null : evt.target;
}
}
But this syntax is unknown to me, could someone explain exactly what
document.activeElement = evt.target == document ? null : evt.target;
does?
? :
is the conditional operator, sometimes called the "ternary operator". As an example, a ? b : c
will return b
if a
is true
, and c
otherwise.
Your code will assign null
to document.activeElement
if evt.target == document
. Otherwise, evt.target
will be assigned.
This is Ternary Operator, here is more info about it.
Its prototype is like this:
(expression) ? true : false
Example:
(myvar == 10) ? document.write('yes it is equal to 10') : document.write('no it is not equal to 10')
Your condition can be re-written like this too which is essentially the same:
if (evt.target == document)
{
document.activeElement = null;
}
else
{
document.activeElement = evt.target;
}
Hope this if-else condition makes it easier for you to understand what Ternary operator is all about. Thanks :)
It's a ternary operator, similar to that in java. Its saying that if evt.target==document then activeElement is null, otherwise activeElement is evt.target.
It is the ternary operator. It might be easier if I parenthesise it for you:
document.activeElement = ((evt.target == document) ? null : evt.target);
The basic format is:
something_boolean ? if_true_return_this : else_return_this;
So you can either use it like an if-else statement, or for assignment.
That syntax is the conditional operator (also known as ternary operator). The expression
expr1 ? expr2 : expr3
evaluates to the evaluated value of expr2 if the evaluated value of expr1 is true or to the evaluated value of expr3 otherwise.
So in your example
evt.target == document ? null : evt.target
will evaluate to null if evt.target == document
is true or to evt.target
otherwise. That means null is assigned to document.activeElement
if evt.target == document
is true and otherwise evt.target
is assigned to document.activeElement
:
if (evt.target == document) {
document.activeElement = null;
} else {
document.activeElement = evt.target;
}
This is the conditional operator, which wikipeida explains as
condition ? value if true : value if false
It is easier to read with brackets, as it makes the order of evaluation clearer
document.activeElement = (evt.target == document ? null : evt.target);
The above line can be expanded expanded to
if ( evt.target == document ){
document.activeElement = null;
}else{
document.activeElement = evt.target;
}
In other words, it assigns the result of the conditional expression to document.activeElement
.
精彩评论