1

このhttp://www.queness.com/post/12078/create-jquery-pinterest-pin-it-pluginプラグインでJavascript/jQueryを理解しようとしてい ます。20行目と22行目は私を混乱させています。コードは次のとおりです。

pi_media = e.data('media') ? e.data('media') : e[0].src,

pi_desc = e.attr('title') ? e.attr('title') : e.attr('alt'),

これらの行がJavascriptで何を意味するのか誰かが私を助けてくれますか

4

4 に答える 4

3

It's the JavaScript ternary operator.

x = condition ? a : b

is equivalent to

if(condition)
    x = a;
else
    x = b;

Note that an assignment is not necessary. As an expression, it simply evaluates and produces a or b depending on the truth value of condition.

于 2013-02-10T04:05:54.230 に答える
2

It's called the Ternary Operator. It means:

  • Evaluate the expression to the left of the ?
  • If the expression evaluated to true, run the first piece of code (between the ? and the :)
  • If the expression evaluated to false, run the second piece of code (after the :)

This is a construct common to many C-style languages.

于 2013-02-10T04:06:41.163 に答える
2

Those are part of the ternary operator.

Basically, if the condition before the ? is evaluated to true, the expression immediately following the ? is the one which is evaluated, and otherwise the expression following the : is evaluated.

于 2013-02-10T04:07:38.923 に答える
1

For example take the code:
var result=condition?arg1:arg2;
First the condition is evaluated.
If the evaluation results to true, then arg1 is returned and assigned to result
If the evaluation results to false, then arg2 is returned and assigned to result

于 2013-02-10T04:09:23.707 に答える