理解jQuery语法? :

时间:2015-07-01 02:12:43

标签: javascript jquery scripting

我想了解什么?而且:在这段代码中,我在代码中看到了很多,但我从来不知道它到底在做什么?

请有人请指点我正确的方向,这段代码来自jQuery validate()DOCS

$(".selector").validate({
  invalidHandler: function(event, validator) {
    // 'this' refers to the form
    var errors = validator.numberOfInvalids();
    if (errors) {
      var message = errors == 1
        ? 'You missed 1 field. It has been highlighted'
        : 'You missed ' + errors + ' fields. They have been highlighted';
      $("div.error span").html(message);
      $("div.error").show();
    } else {
      $("div.error").hide();
    }
  }
});

4 个答案:

答案 0 :(得分:5)

? :不是jquery,只是vanilla javascript。它被称为条件(三元)运算符,可用作标准if / else语句的简写:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_%28ternary%29_operator

基本上它说

val = (boolean expression)? (val if boolean is true) : (val if boolean is false)

所以在你的情况下,如果message为真,那么'You missed 1 field. It has been highlighted'等于errors == 1,否则message等于'You missed ' + errors + ' fields. They have been highlighted'

答案 1 :(得分:2)

这是条件(三元)运算符,它是标准if / else语句的快捷方式。
这是一个演示的例子:

var grade = 85;
console.log("You " + (grade > 50 ? "passed!" : "failed!"));

//Output: You passed!

/* The above statement is same as saying:
if(grade > 50){
    console.log("You " + "passed!");  //or simply "You passed!"
}
else{
    console.log("You " + "failed!"); 
}
*/

答案 2 :(得分:2)

var errors = 1; 
// define `message` 
// if `errors == 1`
var message = errors == 1 
        // `errors == 1`
        ? 'You missed 1 field. It has been highlighted' 
         // `errors != 1`
        : 'You missed ' + errors + ' fields. They have been highlighted';
console.log(message)

答案 3 :(得分:2)

Conditional (ternary) Operator

问号前面的第一部分是您要评估的表达式。问号之后和冒号之前的第二部分是真正的条款。冒号后的第三部分是假条款。