Jquery 简明教程

jQuery - Basics

在开始学习jQuery语法之前,让我们快速了解一下JavaScript的基本概念。这是因为jQuery是一个使用JavaScript功能构建的框架。因此,在使用jQuery时,你可以使用JavaScript中所有可用的功能和其他功能。所以让我们快速了解一下最基本但最常用于jQuery的概念。

Before we start learning about jQuery Syntax, let’s have a quick look on basic concepts of Javascript. This is because, jQuery is a framework built using JavaScript capabilities. So while doing in jQuery, you can use all the functions and other capabilities available in JavaScript. So let’s quickly have a look at the most basic concepts but the most frequently used in jQuery.

String

JavaScript(jQuery)中的字符串是一个不可变的对象,不包含任何字符、一个字符或多个字符。以下是有效的JavaScript字符串示例 -

A string in JavaScript (jQuery) is an immutable object that contains none, one or many characters. Following are the valid examples of a JavaScript String −

"This is JavaScript String"
'This is JavaScript String'
'This is "really" a JavaScript String'
"This is 'really' a JavaScript String"

Numbers

数字在 JavaScript 中是双精度 64 位格式 IEEE 754 值。它们是不可变的,就像字符串一样。以下是 JavaScript 数字的有效示例 −

Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. Following are the valid examples of a JavaScript Numbers −

5350
120.27
0.26

Boolean

JavaScript(jQuery)中的布尔值要么是 true 要么是 false 。如果数字为零,则默认为假。如果空字符串默认为假。

A boolean in JavaScript (jQuery) can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false.

以下是 JavaScript 布尔值的有效示例 −

Following are the valid examples of a JavaScript Boolean −

true      // true
false     // false
0         // false
1         // true
""        // false
"hello"   // true

Objects

JavaScript(jQuery)很好地支持面向对象的概念。你可以使用对象字面量创建对象,如下所示 -

JavaScript (jQuery) supports Object concept very well. You can create an object using the object literal as follows −

var emp = {
   name: "Zara",
   age: 10
};

你可以使用点表示法编写和读取对象的属性,如下所示 −

You can write and read properties of an object using the dot notation as follows −

// Getting object properties
emp.name  // ==> Zara
emp.age   // ==> 10

// Setting object properties
emp.name = "Daisy"  // <== Daisy
emp.age  =  20      // <== 20

Arrays

你可以使用数组字面量定义数组,如下所示 −

You can define arrays using the array literal as follows −

var x = [];
var y = [1, 2, 3, 4, 5];

数组有一个 length 属性,它对于迭代非常有用 −

An array has a length property that is useful for iteration −

var x = [1, 2, 3, 4, 5];

for (var i = 0; i < x.length; i++) {
   // Do something with x[i]
}

Functions

JavaScript(jQuery)中的函数可以是命名函数也可以是匿名函数。可以像下面这样使用function关键字定义命名函数 -

A function in JavaScript (jQuery) can be either named or anonymous. A named function can be defined using function keyword as follows −

function named(){
   // do some stuff here
}

匿名函数可以像普通函数一样定义,但是它没有任何名称。

An anonymous function can be defined in similar way as a normal function but it would not have any name.

匿名函数可以分配给一个变量或传递给一个方法,如下所示。

A anonymous function can be assigned to a variable or passed to a method as shown below.

var handler = function (){
   // do some stuff here
}

JQuery 非常频繁地使用匿名函数,如下所示 −

JQuery makes a use of anonymous functions very frequently as follows −

$(document).ready(function(){
   // do some stuff here
});

Arguments

  • JavaScript (jQuery) 可变参数实际上是具有 length 属性的数组。以下示例对其进行了非常好的解释 −

JavaScript (jQuery) variable arguments is a kind of array which has length property. Following example explains it very well −

function func(x){
   console.log(typeof x, arguments.length);
}

func();                //==> "undefined", 0
func(1);               //==> "number", 1
func("1", "2", "3");   //==> "string", 3

arguments 对象还具有一个 callee 属性,它指的是你当前所在的函数。例如 −

The arguments object also has a callee property, which refers to the function you’re inside of. For example −

function func() {
   return arguments.callee;
}

func();                // ==> func

Context

  • JavaScript (jQuery) 著名的关键字 this 总是指代当前上下文。在函数 this 内,根据函数的调用方式,上下文可能会改变 −

JavaScript (jQuery) famous keyword this always refers to the current context. Within a function this context can change, depending on how the function is called −

$(document).ready(function() {
   // this refers to window.document
});

$("div").click(function() {
   // this refers to a div DOM element
});

你可以使用函数内置方法 call()apply() 方法为函数调用指定上下文。

You can specify the context for a function call using the function-built-in methods call() and apply() methods.

它们之间的区别在于它们如何传递参数。Call 将所有参数作为函数的参数传递,而 apply 接受一个数组作为参数。

The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.

function scope() {
   console.log(this, arguments.length);
}

scope() // window, 0
scope.call("foobar", [1,2]);  //==> "foobar", 1
scope.apply("foobar", [1,2]); //==> "foobar", 2

Scope

  • 变量的作用域是程序中定义该变量的区域。JavaScript (jQuery) 变量只有两个作用域。

The scope of a variable is the region of your program in which it is defined. JavaScript (jQuery) variable will have only two scopes.

  1. Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code.

  2. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

在函数体中,局部变量优先考虑具有相同名称的全局变量 −

Within the body of a function, a local variable takes precedence over a global variable with the same name −

var myVar = "global";     // ==> Declare a global variable

function ( ) {
   var myVar = "local";   // ==> Declare a local variable
   document.write(myVar); // ==> local
}

Callback

  • 回调是一种纯 JavaScript (jQuery) 函数,作为参数或选项传递给某些方法。某些回调只是事件,用于在触发某种状态时给用户机会做出反应。

A callback is a plain JavaScript (jQuery) function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

jQuery 的事件系统到处都使用这种回调函数,例如 −

jQuery’s event system uses such callbacks everywhere for example −

$("body").click(function(event) {
   console.log("clicked: " + event.target);
});

大多数回调函数提供参数和上下文。在事件处理程序示例中,使用一个参数(事件)调用回调函数。

Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event.

一些回调函数需要返回某些内容,其他回调函数使该返回值变为可选。若要阻止提交表单,提交事件处理程序可以返回 false,如下所示 −

Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows −

$("#myform").submit(function() {
   return false;
});

Closures

  • JavaScript (jQuery) 闭包是在从当前作用域外部定义的变量从某个内部作用域访问时创建的。

JavaScript (jQuery) closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.

以下示例演示了如何 counter 变量在 create、increment 和 print 函数中可见,但在它们外部不可见 −

Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −

function create() {
   var counter = 0;

   return {
      increment: function() {
         counter++;
      },
	   print: function() {
         console.log(counter);
      }
   }
}

var c = create();
c.increment();
c.print();     // ==> 1

这种模式允许你创建包含操作数据的方法的对象,外部世界不可见这些数据。需要指出的是, data hiding 是面向对象编程的基础。

This pattern allows you to create objects with methods that operate on data that isn’t visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming.

Proxy Pattern

代理是一种可用于控制对另一个对象的访问的对象。它实现与这个其他对象相同的接口,并将任何方法调用传递给它。这个其他对象通常被称为真实主体。

A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject.

代理可以实例化来代替这个真实主体,并允许远程访问它。我们可以将 jQuery 的 setArray 方法保存在闭包中并按如下方式覆盖它 -

A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery’s setArray method in a closure and overwrites it as follows −

(function() {
   // log all calls to setArray
   var proxied = jQuery.fn.setArray;

   jQuery.fn.setArray = function() {
      console.log(this, arguments);
      return proxied.apply(this, arguments);
   };

})();

上面将代码包装在函数中以隐藏代理变量。然后,代理记录对该方法的所有调用并将调用委托给原始方法。使用 apply(this, arguments) 来保证调用者无法发现原始方法和代理方法之间的差异。

The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments) guarantees that the caller won’t be able to notice the difference between the original and the proxied method.

Built-in Functions

JavaScript 附带了一组有用的内置函数。这些方法可用于处理字符串、数字和日期。

JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates.

以下是重要的 JavaScript 函数 -

Following are important JavaScript functions −

Sr.No.

Method & Description

1

charAt() Returns the character at the specified index.

2

concat() Combines the text of two strings and returns a new string.

3

forEach() Calls a function for each element in the array.

4

indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

5

length() Returns the length of the string.

6

pop() Removes the last element from an array and returns that element.

7

push() Adds one or more elements to the end of an array and returns the new length of the array.

8

reverse() Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first.

9

sort() Sorts the elements of an array.

10

substr() Returns the characters in a string beginning at the specified location through the specified number of characters.

11

toLowerCase() Returns the calling string value converted to lower case.

12

toString() Returns the string representation of the number’s value.

13

toUpperCase() Returns the calling string value converted to uppercase.

The Document Object Model

  • 文档对象模型是各种 HTML 元素的树形结构,如下所示。尝试单击图标 以运行以下 jQuery 代码 −

The Document Object Model is a tree structure of various elements of HTML as follows. Try to click the icon to run the following jQuery code −

<html>
<head>
   <title>The DOM Example</title>
</head>
<body>
   <div>
      <p>This is a paragraph.</p>
      <p>This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

以下列出的是关于上述树结构的重要要点−

Following are the important points about the above tree structure −

  1. The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>.

  2. The <head> and <body> elements are not only descendants, but children of <html>, as well.

  3. Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent.

  4. The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements.

在学习jQuery概念时,了解DOM会有所帮助,如果你不了解DOM,我建议你浏览我们在 DOM Tutorial 上的简单教程。

While learning jQuery concepts, it will be helpful to have understanding on DOM, if you are not aware of DOM then I would suggest to go through our simple tutorial on DOM Tutorial.