Jquery 简明教程
jQuery - Overview
What is jQuery?
jQuery 是一个快速、简洁的 JavaScript 库,由 John Resig 于 2006 年创建,拥有一个精良的座右铭: Write less, do more 。jQuery 简化了 HTML 文档的遍历、事件处理、动画和 Ajax 交互,从而实现快速 Web 开发。jQuery 是一个 JavaScript 工具包,旨在通过编写更少的代码来简化各种任务。以下列出了 jQuery 支持的重要核心功能 −
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery −
-
DOM manipulation − The jQuery made it easy to select DOM elements, negotiate them and modifying their content by using cross-browser open source selector engine called Sizzle.
-
Event handling − The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.
-
AJAX Support − The jQuery helps you a lot to develop a responsive and featurerich site using AJAX technology.
-
Animations − The jQuery comes with plenty of built-in animation effects which you can use in your websites.
-
Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and gzipped).
-
Cross Browser Support − The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
-
Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax.
How to use jQuery?
有两种方法可以使用 jQuery。
There are two ways to use jQuery.
-
Local Installation − You can download jQuery library on your local machine and include it in your HTML code.
-
CDN Based Version − You can include jQuery library into your HTML code directly from Content Delivery Network (CDN).
Local Installation
-
Go to the https://jquery.com/download/ to download the latest version available.
-
Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery.
Example
现在,你可以按照以下步骤将 jquery 库添加到你的 HTML 文件中 −
Now you can include jquery library in your HTML file as follows −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript" src = "/jquery/jquery-2.1.3.min.js">
</script>
<script type = "text/javascript">
$(document).ready(function() {
document.write("Hello, World!");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
这将生成以下结果:
This will produce following result −
CDN Based Version
可以直接从内容发布网络 (CDN) 将 jQuery 库添加到你的 HTML 代码中。Google 和 Microsoft 为最新版本提供内容发布。
You can include jQuery library into your HTML code directly from Content Delivery Network (CDN). Google and Microsoft provides content deliver for the latest version.
Example
现在,让我们使用来自 Google CDN 的 jQuery 库重写以上示例。
Now let us rewrite above example using jQuery library from Google CDN.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript">
$(document).ready(function() {
document.write("Hello, World!");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
这将生成以下结果:
This will produce following result −
How to Call a jQuery Library Functions?
正如我们在使用 jQuery 时的几乎所有操作,都会读取或操作 Document Object Model (DOM),我们需要确保我们在 DOM 准备就绪后立即开始添加事件等。
As almost everything, we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
如果想让你的页面上某个事件发挥作用,应在 $(document).ready() 函数内调用它。只要 DOM 载入,且在页面内容载入之前,该函数内的所有内容都将立即加载。
If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
为此,我们按照如下方式为文档注册一个 ready 事件:
To do this, we register a ready event for the document as follows −
$(document).ready(function() {
// do stuff when DOM is ready
});
若要调用任何 jQuery 库函数,请使用 HTML 脚本标记,如下所示 −
To call upon any jQuery library function, use HTML script tags as shown below −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function() {alert("Hello, world!");});
});
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
How to Use Custom Scripts?
最好按照以下步骤将我们自定义的代码写入自定义 JavaScript 文件: custom.js −
It is better to write our custom code in the custom JavaScript file : custom.js, as follows −
/* Filename: custom.js */
$(document).ready(function() {
$("div").click(function() {
alert("Hello, world!");
});
});
现在,我们可以按照以下步骤将 custom.js 文件添加到我们的 HTML 文件中 −
Now we can include custom.js file in our HTML file as follows −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" src = "/jquery/custom.js">
</script>
</head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Using Multiple Libraries
您可以一次使用多个库,而不会互相冲突。例如,你可以同时使用 jQuery 和 MooTool javascript 库。你可以查看 jQuery noConflict 方法了解更多详情。
You can use multiple libraries all together without conflicting each others. For example, you can use jQuery and MooTool javascript libraries together. You can check jQuery noConflict Method for more detail.
What is Next ?
如果你没看懂以上示例,不用过于担心。你很快就会在后续章节中理解它们。
Do not worry too much if you did not understand above examples. You are going to grasp them very soon in subsequent chapters.
下一章将尝试涵盖一些来自传统 JavaScript 的基本概念。
Next chapter would try to cover few basic concepts which are coming from conventional JavaScript.
jQuery - Basics
jQuery 是一个构建在 JavaScript 能力之上的框架。所以,你可以使用 JavaScript 中所有可用的函数和其他能力。本章将解释一些在 jQuery 中最基本但也经常使用的概念。
jQuery is a framework built using JavaScript capabilities. So, you can use all the functions and other capabilities available in JavaScript. This chapter would explain most basic concepts but frequently used in jQuery.
String
字符串在 JavaScript 中是一个不可变对象,它不包含字符或只包含一个或多个字符。以下是 JavaScript 字符串的有效示例 −
A string in JavaScript 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 中可以是 true 或 false 。如果一个数字是零,它默认为 false。如果一个空字符串默认为 false。
A boolean in JavaScript 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 非常好地支持对象概念。你可以使用对象字面量创建对象,如下所示 −
JavaScript 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 中的函数可以是命名函数或匿名函数。一个命名函数可以使用 function 关键字定义,如下所示 −
A function in JavaScript 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 中的 variable arguments 是一种具有 length 属性的数组。以下示例解释得非常好 −
JavaScript 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 著名关键字 this 总是指当前上下文。在一个函数中 this 上下文会改变,这取决于函数的调用方式 −
JavaScript 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 变量只有两个作用域。
The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
-
Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code.
-
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 函数。一些回调函数仅仅是事件,用于在触发特定状态时给用户一个机会做出反应。
A callback is a plain JavaScript 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
只要从内部范围访问在当前范围外部定义的变量,就会创建闭包。
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 各个元素的树形结构,如下所示 -
The Document Object Model is a tree structure of various elements of HTML as follows −
<html>
<head>
<title>The jQuery 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>
这将生成以下结果:
This will produce following result −
以下列出的是关于上述树结构的重要要点−
Following are the important points about the above tree structure −
-
The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>.
-
The <head> and <body> elements are not only descendants, but children of <html>, as well.
-
Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent.
-
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.
jQuery - Selectors
jQuery库利用层叠样式表(CSS)选择器的强大功能,让我们能够快速轻松地访问Document Object Model(DOM)中元素或元素组。
The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).
jQuery选择器是一个函数,它使用表达式从一个基于给定条件的DOM中找出匹配的元素。简单地说,选择器用于使用jQuery选择一个或多个HTML元素。一旦选择了一个元素,我们就可以对选定的元素执行各种操作。
A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria. Simply you can say, selectors are used to select one or more HTML elements using jQuery. Once an element is selected then we can perform various operations on that selected element.
The $() factory function
jQuery选择器以美元符号和括号开始− $() 。工厂函数 $() 在给定文档中选择元素时使用以下三个构建块−
jQuery selectors start with the dollar sign and parentheses − $(). The factory function $() makes use of following three building blocks while selecting elements in a given document −
Sr.No. |
Selector & Description |
1 |
Tag Name Represents a tag name available in the DOM. For example $('p') selects all paragraphs <p> in the document. |
2 |
Tag ID Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id. |
3 |
Tag Class Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class. |
所有上述项目都可以单独或与其他选择器结合使用。除了一些调整外,所有jQuery选择器都基于相同的原则。
All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.
NOTE −工厂函数 $() 是函数 jQuery() 的同义词。因此,如果你正在使用任何其他JavaScript库,其中 $ 符号与其他一些东西冲突,那么你可以用 jQuery 名称替换 $ 符号,并且你可以使用函数 jQuery() 代替 $() 。
NOTE − The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $().
Example
以下是一个简单的示例,它使用了标签选择器。这将选择所有带标签名 p 的元素。
Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p").css("background-color", "yellow");
});
</script>
</head>
<body>
<div>
<p class = "myclass">This is a paragraph.</p>
<p id = "myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
How to Use Selectors?
选择器非常有用,在使用jQuery时,每一步都必不可少。它们从你的HTML文档中获取你想要的准确元素。
The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
以下表格列出了几个基本选择器,并用示例对此进行解释。
Following table lists down few basic selectors and explains them with examples.
Sr.No. |
Selector & Description |
1 |
NameSelects all elements which match with the given element Name. |
2 |
#IDSelects a single element which matches with the given ID. |
3 |
.ClassSelects all elements which match with the given Class. |
4 |
Universal (*)Selects all elements available in a DOM. |
5 |
Multiple Elements E, F, GSelects the combined results of all the specified selectors E, F or G. |
Selectors Examples
与上述语法和示例类似,以下示例将帮助你理解使用不同类型的其他有用的选择器:
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors −
你可以以通用方式将所有上述选择器与任何 HTML/XML 元素配合使用。例如,如果选择器 Multiple Elements E, F, G 适用于 <li> 元素,则 $("li:first") 也适用于 <p> 元素。
You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element.
jQuery - Attributes
当涉及到 DOM 元素时,我们可以操作的一些最基本组件是分配给这些元素的属性和特性。
Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.
这些属性中的大多数都可以通过 JavaScript 作为 DOM 节点属性获得。一些更常见的属性是:
Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are −
-
className
-
tagName
-
id
-
href
-
title
-
rel
-
src
考虑以下图像元素的 HTML 标记:
Consider the following HTML markup for an image element −
<img id = "imageid" src = "image.gif" alt = "Image" class = "myclass"
title = "This is an image"/>
在这个元素的标记中,标签名称是 img,id、src、alt、class 和 title 的标记表示元素的属性,其中每一个都包含一个名称和一个值。
In this element’s markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element’s attributes, each of which consists of a name and a value.
jQuery 为我们提供了一种轻松操作元素属性的方式,并让我们可以访问该元素,以便我们还可以更改它的属性。
jQuery gives us the means to easily manipulate an element’s attributes and gives us access to the element so that we can also change its properties.
Get Attribute Value
$("p:first") 方法可用于从匹配集中第一个元素中获取属性的值,或将属性值设置为所有匹配的元素。
The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements.
Example
以下是一个简单的示例,其中获取 <em> 标签的 title 属性并在 <div id = "divid"> 值中设置相同的值:
Following is a simple example which fetches title attribute of <em> tag and set <div id = "divid"> value with the same value −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
var title = $("em").attr("title");
$("#divid").text(title);
});
</script>
</head>
<body>
<div>
<em title = "Bold and Brave">This is first paragraph.</em>
<p id = "myid">This is second paragraph.</p>
<div id = "divid"></div>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Set Attribute Value
attr() 方法可用于使用传递的值将命名属性设置为包装集中所有元素。
The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.
Example
以下是一个简单的示例,其中将图像标记的 attr(name, value) 属性设置为正确的位置:
Following is a simple example which set src attribute of an image tag to a correct location −
<html>
<head>
<title>The jQuery Example</title>
<base href="https://www.tutorialspoint.com" />
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#myimg").attr("src", "/jquery/images/jquery.jpg");
});
</script>
</head>
<body>
<div>
<img id = "myimg" src = "/images/jquery.jpg" alt = "Sample image" />
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Applying Styles
src 方法可用于将定义的样式表应用到所有匹配的元素。你可以指定多个用空格分隔的类。
The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.
Example
以下是一个简单的示例,其中设置 para <p> 标记的 addClass( classes ) 属性:
Following is a simple example which sets class attribute of a para <p> tag −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("em").addClass("selected");
$("#myid").addClass("highlight");
});
</script>
<style>
.selected { color:red; }
.highlight { background:yellow; }
</style>
</head>
<body>
<em title = "Bold and Brave">This is first paragraph.</em>
<p id = "myid">This is second paragraph.</p>
</body>
</html>
这将生成以下结果:
This will produce following result −
Attribute Methods
下表列出了几种用于操作属性和特性的有用方法:
Following table lists down few useful methods which you can use to manipulate attributes and properties −
Sr.No. |
Methods & Description |
1 |
attr( properties )Set a key/value object as properties to all matched elements. |
2 |
attr( key, fn )Set a single property to a computed value, on all matched elements. |
3 |
removeAttr( name )Remove an attribute from each of the matched elements. |
4 |
hasClass( class )Returns true if the specified class is present on at least one of the set of matched elements. |
5 |
removeClass( class )Removes all or the specified class(es) from the set of matched elements. |
6 |
toggleClass( class )Adds the specified class if it is not present, removes the specified class if it is present. |
7 |
html( )Get the html contents (innerHTML) of the first matched element. |
8 |
html( val )Set the html contents of every matched element. |
9 |
text( )Get the combined text contents of all matched elements. |
10 |
text( val )Set the text contents of all matched elements. |
11 |
val( )Get the input value of the first matched element. |
12 |
val( val )Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked. |
jQuery - DOM Traversing
jQuery是一个非常强大的工具,它提供了一些DOM遍历方法,可以帮助我们随机以及顺序地选择文档中的元素。大多数DOM遍历方法不修改jQuery对象,它们用来基于给定条件从文档中过滤出元素。
jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method. Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions.
Find Elements by Index
考虑一个具有如下HTML内容的简单文档−
Consider a simple document with the following HTML content −
<html>
<head>
<title>The JQuery Example</title>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
-
Above every list has its own index, and can be located directly by using eq(index) method as below example.
-
Every child element starts its index from zero, thus, list item 2 would be accessed by using $("li").eq(1) and so on.
Example
以下是一个简单的示例,它为第二个列表项添加了颜色。
Following is a simple example which adds the color to second list item.
<html>
<head>
<title>The JQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("li").eq(2).addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Filtering out Elements
filter( selector ) 方法可用于过滤出与指定的选择器不匹配的一组匹配元素中的所有元素。选择器可以使用任何选择器语法编写。
The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax.
Example
以下是一个简单的示例,它为与middle类关联的列表应用颜色−
Following is a simple example which applies color to the lists associated with middle class −
<html>
<head>
<title>The JQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("li").filter(".middle").addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<div>
<ul>
<li class = "top">list item 1</li>
<li class = "top">list item 2</li>
<li class = "middle">list item 3</li>
<li class = "middle">list item 4</li>
<li class = "bottom">list item 5</li>
<li class = "bottom">list item 6</li>
</ul>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Locating Descendant Elements
find( selector ) 方法可用于找到特定类型元素的所有后代元素。选择器可以使用任何选择器语法编写。
The find( selector ) method can be used to locate all the descendant elements of a particular type of elements. The selector can be written using any selector syntax.
Example
以下是一个示例,它选择所有在不同的<p>元素中可用的<span>元素−
Following is an example which selects all the <span> elements available inside different <p> elements −
<html>
<head>
<title>The JQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p").find("span").addClass("selected");
});
</script>
<style>
.selected { color:red; }
</style>
</head>
<body>
<p>This is 1st paragraph and <span>THIS IS RED</span></p>
<p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>
</body>
</html>
这将生成以下结果:
This will produce following result −
JQuery DOM Filter Methods
下表列出了有用的方法,您可以使用这些方法从DOM元素列表中过滤出各种元素−
Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements −
Sr.No. |
Method & Description |
1 |
eq( index )Reduce the set of matched elements to a single element. |
2 |
filter( selector )Removes all elements from the set of matched elements that do not match the specified selector(s). |
3 |
filter( fn )Removes all elements from the set of matched elements that do not match the specified function. |
4 |
is( selector )Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. |
5 |
map( callback )Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements). |
6 |
not( selector )Removes elements matching the specified selector from the set of matched elements. |
7 |
slice( start, [end] )Selects a subset of the matched elements. |
JQuery DOM Traversing Methods
下表列出了其他有用的方法,您可以使用这些方法在DOM中找到各种元素−
Following table lists down other useful methods which you can use to locate various elements in a DOM −
Sr.No. |
Methods & Description |
1 |
add( selector )Adds more elements, matched by the given selector, to the set of matched elements. |
2 |
andSelf( )Add the previous selection to the current selection. |
3 |
children( [selector])Get a set of elements containing all of the unique immediate children of each of the matched set of elements. |
4 |
closest( selector )Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. |
5 |
contents( )Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe. |
6 |
end( )Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state. |
7 |
find( selector )Searches for descendant elements that match the specified selectors. |
8 |
next( [selector] )Get a set of elements containing the unique next siblings of each of the given set of elements. |
9 |
nextAll( [selector] )Find all sibling elements after the current element. |
10 |
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element. |
11 |
parent( [selector] )Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements. |
12 |
parents( [selector] )Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element). |
13 |
prev( [selector] )Get a set of elements containing the unique previous siblings of each of the matched set of elements. |
14 |
prevAll( [selector] )Find all sibling elements in front of the current element. |
15 |
siblings( [selector] )Get a set of elements containing all of the unique siblings of each of the matched set of elements. |
jQuery - CSS Selectors Methods
jQuery 库支持几乎所有级联样式表 (CSS) 规范 1 到 3 中包含的选择器,如万维网联盟网站上所概述。
The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium’s site.
使用 JQuery 库,开发人员可以增强其网站,而不用担心浏览器及其版本,只要浏览器已启用 JavaScript 即可。
Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled.
大多数 jQuery CSS 方法都不会修改 jQuery 对象的内容,它们用于对 DOM 元素应用 CSS 属性。
Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements.
Apply CSS Properties
使用 jQuery 方法 css( PropertyName, PropertyValue ) 应用任何 CSS 属性非常简单。
This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue ).
以下是此方法的语法−
Here is the syntax for the method −
selector.css( PropertyName, PropertyValue );
在这里,你可以将 PropertyName 作为 javascript 字符串来传递,并且根据其值,PropertyValue 可以是字符串或整数。
Here you can pass PropertyName as a javascript string and based on its value, PropertyValue could be string or integer.
Example
以下是一个向第二个列表项添加字体颜色的示例。
Following is an example which adds font color to the second list item.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("li").eq(2).css("color", "red");
});
</script>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Apply Multiple CSS Properties
你可以使用单个 jQuery 方法 CSS( {key1:val1, key2:val2….) 应用多个 CSS 属性。你可以在单个调用中应用任意数量的属性。
You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2….). You can apply as many properties as you like in a single call.
以下是此方法的语法−
Here is the syntax for the method −
selector.css( {key1:val1, key2:val2....keyN:valN})
在这里,你可以传递键作为属性,传递值作为 val,如上所述。
Here you can pass key as property and val as its value as described above.
Example
以下是一个向第二个列表项添加字体颜色和背景颜色的示例。
Following is an example which adds font color as well as background color to the second list item.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("li").eq(2).css({"color":"red", "background-color":"green"});
});
</script>
</head>
<body>
<div>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Setting Element Width & Height
width( val ) 和 height( val ) 方法可用于分别设置任何元素的宽度和高度。
The width( val ) and height( val ) method can be used to set the width and height respectively of any element.
Example
以下是一个简单的示例,它设置了第一个 div 元素的宽度,而其余元素的宽度由样式表设置
Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div:first").width(100);
$("div:first").css("background-color", "blue");
});
</script>
<style>
div {
width:70px; height:50px; float:left;
margin:5px; background:red; cursor:pointer;
}
</style>
</head>
<body>
<div></div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
JQuery CSS Methods
下表列出了你可以用来处理 CSS 属性的所有方法−
Following table lists down all the methods which you can use to play with CSS properties −
Sr.No. |
Method & Description |
1 |
css( name )Return a style property on the first matched element. |
2 |
css( name, value )Set a single style property to a value on all matched elements. |
3 |
css( properties )Set a key/value object as style properties to all matched elements. |
4 |
height( val )Set the CSS height of every matched element. |
5 |
height( )Get the current computed, pixel, height of the first matched element. |
6 |
innerHeight( )Gets the inner height (excludes the border and includes the padding) for the first matched element. |
7 |
innerWidth( )Gets the inner width (excludes the border and includes the padding) for the first matched element. |
8 |
offset( )Get the current offset of the first matched element, in pixels, relative to the document. |
9 |
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element. |
10 |
outerHeight( [margin] )Gets the outer height (includes the border and padding by default) for the first matched element. |
11 |
outerWidth( [margin] )Get the outer width (includes the border and padding by default) for the first matched element. |
12 |
position( )Gets the top and left position of an element relative to its offset parent. |
13 |
scrollLeft( val )When a value is passed in, the scroll left offset is set to that value on all matched elements. |
14 |
scrollLeft( )Gets the scroll left offset of the first matched element. |
15 |
scrollTop( val )When a value is passed in, the scroll top offset is set to that value on all matched elements. |
16 |
scrollTop( )Gets the scroll top offset of the first matched element. |
17 |
width( val )Set the CSS width of every matched element. |
18 |
width( )Get the current computed, pixel, width of the first matched element. |
jQuery - DOM Manipulation
JQuery 提供了以有效方式处理 DOM 的方法。你不必编写庞大的代码来修改任何元素属性的值或从段落或分区中提取 HTML 代码。
JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element’s attribute or to extract HTML code from a paragraph or division.
JQuery 提供诸如 .attr()、.html() 和 .val() 等方法,这些方法扮演 getter 的角色,用于检索 DOM 元素的信息以便稍后使用。
JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use.
Content Manipulation
html( ) 方法获取第一个匹配元素的 html 内容 (innerHTML)。
The html( ) method gets the html contents (innerHTML) of the first matched element.
以下是此方法的语法−
Here is the syntax for the method −
selector.html( )
Example
以下是使用 .html() 和 .text(val) 方法的一个示例。这里 .html() 从对象中检索 HTML 内容,然后 .text( val ) 方法使用传递的参数设置对象的 value −
Following is an example which makes use of .html() and .text(val) methods. Here .html() retrieves HTML content from the object and then .text( val ) method sets value of the object using passed parameter −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
var content = $(this).html();
$("#result").text( content );
});
});
</script>
<style>
#division{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>Click on the square below:</p>
<span id = "result"> </span>
<div id = "division" style = "background-color:blue;">
This is Blue Square!!
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
DOM Element Replacement
您可以用指定的 HTML 或 DOM 元素替换一个完整的 DOM 元素。 replaceWith( content ) 方法很好地满足了这个目的。
You can replace a complete DOM element with the specified HTML or DOM elements. The replaceWith( content ) method serves this purpose very well.
以下是此方法的语法−
Here is the syntax for the method −
selector.replaceWith( content )
这里 content 是您想要替换原始元素的内容。这可能是一个 HTML 或简单文本。
Here content is what you want to have instead of original element. This could be HTML or simple text.
Example
以下是一个用 "<h1>jQuery 太棒了</h1>" 替换 div 元素的示例 −
Following is an example which would replace division element with "<h1>JQuery is Great </h1>" −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
$(this).replaceWith("<h1>JQuery is Great</h1>");
});
});
</script>
<style>
#division{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>Click on the square below:</p>
<span id = "result"> </span>
<div id = "division" style = "background-color:blue;">
This is Blue Square!!
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Removing DOM Elements
在某些情况下,您可能想要从文档中删除一个或多个 DOM 元素。jQuery 提供两种方法来处理这种情况。
There may be a situation when you would like to remove one or more DOM elements from the document. JQuery provides two methods to handle the situation.
empty( ) 方法从匹配的元素集合中删除所有子节点,而 remove( expr ) 方法从 DOM 中删除所有匹配的元素。
The empty( ) method remove all child nodes from the set of matched elements where as the method remove( expr ) method removes all matched elements from the DOM.
以下是此方法的语法−
Here is the syntax for the method −
selector.remove( [ expr ])
or
selector.empty( )
您可以传递可选参数 expr 来筛选要删除的元素集合。
You can pass optional parameter expr to filter the set of elements to be removed.
Example
以下是一个在元素被单击后立即将其删除的示例 −
Following is an example where elements are being removed as soon as they are clicked −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
$(this).remove( );
});
});
</script>
<style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>Click on any square below:</p>
<span id = "result"> </span>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Inserting DOM Elements
在某些情况下,您可能想要在现有的文档中插入一个或多个新的 DOM 元素。jQuery 提供多种方法来在不同位置插入元素。
There may be a situation when you would like to insert new one or more DOM elements in your existing document. JQuery provides various methods to insert elements at various locations.
after( content ) 方法在每个匹配的元素之后插入内容,而 before( content ) 方法在每个匹配的元素之前插入内容。
The after( content ) method insert content after each of the matched elements where as the method before( content ) method inserts content before each of the matched elements.
以下是此方法的语法−
Here is the syntax for the method −
selector.after( content )
or
selector.before( content )
这里 content 是您要插入的内容。这可能是一个 HTML 或简单文本。
Here content is what you want to insert. This could be HTML or simple text.
Example
以下是一个在被单击的元素之前插入 <div> 元素的示例 −
Following is an example where <div> elements are being inserted just before the clicked element −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
$(this).before('<div class="div"></div>' );
});
});
</script>
<style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>Click on any square below:</p>
<span id = "result"> </span>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
这将生成以下结果:
This will produce following result −
DOM Manipulation Methods
下表列出了所有可用于操作 DOM 元素的方法 −
Following table lists down all the methods which you can use to manipulate DOM elements −
Sr.No. |
Method & Description |
1 |
after( content )Insert content after each of the matched elements. |
2 |
append( content )Append content to the inside of every matched element. |
3 |
appendTo( selector )Append all of the matched elements to another, specified, set of elements. |
4 |
before( content )Insert content before each of the matched elements. |
5 |
clone( bool )Clone matched DOM Elements, and all their event handlers, and select the clones. |
6 |
clone( )Clone matched DOM Elements and select the clones. |
7 |
empty( )Remove all child nodes from the set of matched elements. |
8 |
html( val )Set the html contents of every matched element. |
9 |
html( )Get the html contents (innerHTML) of the first matched element. |
10 |
insertAfter( selector )Insert all of the matched elements after another, specified, set of elements. |
11 |
insertBefore( selector )Insert all of the matched elements before another, specified, set of elements. |
12 |
prepend( content )Prepend content to the inside of every matched element. |
13 |
prependTo( selector )Prepend all of the matched elements to another, specified, set of elements. |
14 |
remove( expr )Removes all matched elements from the DOM. |
15 |
replaceAll( selector )Replaces the elements matched by the specified selector with the matched elements. |
16 |
replaceWith( content )Replaces all matched elements with the specified HTML or DOM elements. |
17 |
text( val )Set the text contents of all matched elements. |
18 |
text( )Get the combined text contents of all matched elements. |
19 |
wrap( elem )Wrap each matched element with the specified element. |
20 |
wrap( html )Wrap each matched element with the specified HTML content. |
21 |
wrapAll( elem )Wrap all the elements in the matched set into a single wrapper element. |
22 |
wrapAll( html )Wrap all the elements in the matched set into a single wrapper element. |
23 |
wrapInner( elem )Wrap the inner child contents of each matched element (including text nodes) with a DOM element. |
24 |
wrapInner( html )Wrap the inner child contents of each matched element (including text nodes) with an HTML structure. |
jQuery - Events Handling
借助事件,我们就可以创建动态网页。事件就是应用程序可侦测的动作。
We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application.
以下为可侦测动作事件范例:
Following are the examples events −
-
A mouse click
-
A web page loading
-
Taking mouse over an element
-
Submitting an HTML form
-
A keystroke on your keyboard, etc.
当触发这些事件时,就可以使用自定义功能执行几乎所有您想对该事件执行的操作。这些自定义功能就是事件处理程序。
When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.
Binding Event Handlers
使用 jQuery 事件模型,我们可以用 bind() 方法对 DOM 元素设置事件处理程序,如下所示:
Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$('div').bind('click', function( event ){
alert('Hi there!');
});
});
</script>
<style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;">ONE</div>
<div class = "div" style = "background-color:green;">TWO</div>
<div class = "div" style = "background-color:red;">THREE</div>
</body>
</html>
这段代码将使分段元素对 click 事件产生反应;当之后用户在这个分段中单击时,将会显示警报。
This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown.
这将生成以下结果:
This will produce following result −
bind() 命令的完整语法如下:
The full syntax of the bind() command is as follows −
selector.bind( eventType[, eventData], handler)
以下是参数的描述 -
Following is the description of the parameters −
-
eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
-
eventData − This is optional parameter is a map of data that will be passed to the event handler.
-
handler − A function to execute each time the event is triggered.
Removing Event Handlers
通常,一旦建立一个事件处理程序,它将在整个页面的生命周期中保持有效。有时,您可能需要移除事件处理程序。
Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.
jQuery 提供 unbind() 命令来移除现有的事件处理程序。unbind() 的语法如下所示 -
jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows −
selector.unbind(eventType, handler)
or
selector.unbind(eventType)
以下是参数的描述 -
Following is the description of the parameters −
-
eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
-
handler − If provided, identifies the specific listener that’s to be removed.
The Event Object
回调函数接收一个参数;当调用处理程序时,JavaScript 事件对象将会通过该参数传递。
The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.
The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed.
The Event Attributes
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$('div').bind('click', function( event ){
alert('Event type is ' + event.type);
alert('pageX : ' + event.pageX);
alert('pageY : ' + event.pageY);
alert('Target : ' + event.target.innerHTML);
});
});
</script>
<style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;">ONE</div>
<div class = "div" style = "background-color:green;">TWO</div>
<div class = "div" style = "background-color:red;">THREE</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
The Event Methods
存在可以用在事件对象上的多个方法列表:
There is a list of methods which can be called on an Event Object −
Sr.No. |
Method & Description |
1 |
preventDefault()Prevents the browser from executing the default action. |
2 |
isDefaultPrevented()Returns whether event.preventDefault() was ever called on this event object. |
3 |
stopPropagation()Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. |
4 |
isPropagationStopped()Returns whether event.stopPropagation() was ever called on this event object. |
5 |
stopImmediatePropagation()Stops the rest of the handlers from being executed. |
6 |
isImmediatePropagationStopped()Returns whether event.stopImmediatePropagation() was ever called on this event object. |
Event Manipulation Methods
下表列举出了重要的与事件相关的方法:
Following table lists down important event-related methods −
Sr.No. |
Method & Description |
1 |
bind( type, [data], fn )Binds a handler to one or more events (like click) for each matched element. Can also bind custom events. |
2 |
off( events [, selector ] [, handler(eventObject) ] )This does the opposite of live, it removes a bound live event. |
3 |
hover( over, out )Simulates hovering for example moving the mouse on, and off, an object. |
4 |
on( events [, selector ] [, data ], handler )Binds a handler to an event (like click) for all current − and future − matched element. Can also bind custom events. |
5 |
one( type, [data], fn )Binds a handler to one or more events to be executed once for each matched element. |
6 |
ready( fn )Binds a function to be executed whenever the DOM is ready to be traversed and manipulated. |
7 |
trigger( event, [data] )Trigger an event on every matched element. |
8 |
triggerHandler( event, [data] )Triggers all bound event handlers on an element. |
9 |
unbind( [type], [fn] )This does the opposite of bind, it removes bound events from each of the matched elements. |
Event Helper Methods
jQuery 还提供了一组事件帮助程序函数,可以用来触发事件或绑定上面提到的任何事件类型。
jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.
jQuery - Ajax
异步 JavaScript 和 XML 的缩写是 AJAX,这项技术帮助我们在不刷新浏览器页面时,从服务器加载数据。
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh.
如果您刚开始接触 AJAX,那么我建议您在继续之前先阅读我们的 Ajax Tutorial 。
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
jQuery 是一个很好的工具,它提供了丰富的 AJAX 方法来开发下一代 Web 应用程序。
JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application.
Loading Simple Data
使用 jQuery AJAX 可以轻松加载任何静态数据或动态数据。jQuery 提供 load() 方法来完成这项工作 −
This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to do the job −
Syntax
以下是 load() 方法的简单语法 −
Here is the simple syntax for load() method −
[selector].load( URL, [data], [callback] );
以下是所有参数的说明 −
Here is the description of all the parameters −
-
URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.
-
data − This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.
-
callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code.
Example
考虑以下带有少量 JQuery 编码的 HTML 文件 −
Consider the following HTML file with a small JQuery coding −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$('#stage').load('/jquery/result.html');
});
});
</script>
</head>
<body>
<p>Click on the button to load /jquery/result.html file −</p>
<div id = "stage" style = "background-color:cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
此处 load() 对指定 URL /jquery/result.html 文件发起 Ajax 请求。加载此文件后,所有内容都将填充在标记为 ID stage 的 <div> 中。假设我们的 /jquery/result.html 文件只有一行 HTML −
Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line −
<h1>THIS IS RESULT...</h1>
-
* *当你点击给定的按钮,result.html文件就会被加载。
When you click the given button, then result.html file gets loaded.
Getting JSON Data
在某些情况下,服务器将根据您的请求返回 JSON 字符串。JQuery 实用函数 getJSON() 解析返回的 JSON 字符串,并将结果字符串作为第一个参数提供给回调函数,以采取进一步的操作。
There would be a situation when server would return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take further action.
Syntax
以下是 getJSON() 方法的简单语法 −
Here is the simple syntax for getJSON() method −
[selector].getJSON( URL, [data], [callback] );
以下是所有参数的说明 −
Here is the description of all the parameters −
-
URL − The URL of the server-side resource contacted via the GET method.
-
data − An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string.
-
callback − A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second.
Example
考虑以下带有少量 JQuery 编码的 HTML 文件 −
Consider the following HTML file with a small JQuery coding −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('/jquery/result.json', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.age+ '</p>');
$('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.json file −</p>
<div id = "stage" style = "background-color:#eee;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
此处,JQuery 实用方法 getJSON() 对指定 URL result.json 文件发起 Ajax 请求。加载此文件后,所有内容都将传递给回调函数,最终填充在标记为 ID stage 的 <div> 中。假设我们的 result.json 文件有以下 json 格式的内容 −
Here JQuery utility method getJSON() initiates an Ajax request to the specified URL result.json file. After loading this file, all the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage. Assuming, our result.json file has following json formatted content −
{
"name": "Zara Ali",
"age" : "67",
"sex": "female"
}
单击给定的按钮时,将加载 result.json 文件。
When you click the given button, then result.json file gets loaded.
Passing Data to the Server
很多时候,您会从用户那里收集输入,并将这些输入传递给服务器以进行进一步处理。JQuery AJAX 使得使用任何可用 Ajax 方法的 data 参数将收集的数据传递给服务器变得相当容易。
Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it easy enough to pass collected data to the server using data parameter of any available Ajax method.
Example
此示例演示如何将用户输入传递到网络服务器脚本,该脚本将发送回相同的结果,我们将会打印它 −
This example demonstrate how can pass user input to a web server script which would send the same result back and we would print it −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
var name = $("#name").val();
$("#stage").load('/jquery/result.php', {"name":name} );
});
});
</script>
</head>
<body>
<p>Enter your name and click on the button:</p>
<input type = "input" id = "name" size = "40" /><br />
<div id = "stage" style = "background-color:cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Show Result" />
</body>
</html>
以下是用 result.php 脚本编写的代码 −
Here is the code written in result.php script −
<?php
if( $_REQUEST["name"] ){
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
现在,您可以在给定的输入框中输入任何文本,然后单击“显示结果”按钮以查看您在输入框中输入的内容。
Now you can enter any text in the given input box and then click "Show Result" button to see what you have entered in the input box.
JQuery AJAX Methods
您已经看到使用 JQuery 的 AJAX 基本概念。下表列出了所有重要的 JQuery AJAX 方法,您可以根据您的编程需要使用它们 −
You have seen basic concept of AJAX using JQuery. Following table lists down all important JQuery AJAX methods which you can use based your programming need −
Sr.No. |
Methods & Description |
1 |
jQuery.ajax( options )Load a remote page using an HTTP request. |
2 |
jQuery.ajaxSetup( options )Setup global settings for AJAX requests. |
3 |
jQuery.get( url, [data], [callback], [type] )Load a remote page using an HTTP GET request. |
4 |
jQuery.getJSON( url, [data], [callback] )Load JSON data using an HTTP GET request. |
5 |
jQuery.getScript( url, [callback] )Loads and executes a JavaScript file using an HTTP GET request. |
6 |
jQuery.post( url, [data], [callback], [type] )Load a remote page using an HTTP POST request. |
7 |
load( url, [data], [callback] )Load HTML from a remote file and inject it into the DOM. |
8 |
serialize( )Serializes a set of input elements into a string of data. |
9 |
serializeArray( )Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with. |
JQuery AJAX Events
在 AJAX 调用进程的生命周期中,您可以调用各种 JQuery 方法。基于不同的事件/阶段有以下可用方法 −
You can call various JQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available −
您可以浏览所有 AJAX Events 。
You can go through all the AJAX Events.
Sr.No. |
Methods & Description |
1 |
ajaxComplete( callback )Attach a function to be executed whenever an AJAX request completes. |
2 |
ajaxStart( callback )Attach a function to be executed whenever an AJAX request begins and there is none already active. |
3 |
ajaxError( callback )Attach a function to be executed whenever an AJAX request fails. |
4 |
ajaxSend( callback )Attach a function to be executed before an AJAX request is sent. |
5 |
ajaxStop( callback )Attach a function to be executed whenever all AJAX requests have ended. |
6 |
ajaxSuccess( callback )Attach a function to be executed whenever an AJAX request completes successfully. |
jQuery - Effects
jQuery 提供了一个极度简单的界面用于执行各种奇妙的效果。jQuery 方法让我们能够使用最少配置快速应用常用效果。本教程涵盖所有重要的 jQuery 方法以创建视觉效果。
jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration. This tutorial covers all the important jQuery methods to create visual effects.
Showing and Hiding Elements
显示和隐藏元素的命令非常符合我们的期望 − show() 用于显示包装中的元素, hide() 用于隐藏它们。
The commands for showing and hiding elements are pretty much what we would expect − show() to show the elements in a wrapped set and hide() to hide them.
Syntax
以下是 show() 方法的简单语法 −
Here is the simple syntax for show() method −
[selector].show( speed, [callback] );
以下是所有参数的说明 −
Here is the description of all the parameters −
-
speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
-
callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.
以下是 hide() 方法的简单语法 −
Following is the simple syntax for hide() method −
[selector].hide( speed, [callback] );
以下是所有参数的说明 −
Here is the description of all the parameters −
-
speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
-
callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.
Example
考虑以下带有少量 JQuery 编码的 HTML 文件 −
Consider the following HTML file with a small JQuery coding −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#show").click(function () {
$(".mydiv").show( 1000 );
});
$("#hide").click(function () {
$(".mydiv").hide( 1000 );
});
});
</script>
<style>
.mydiv{
margin:10px;
padding:12px;
border:2px solid #666;
width:100px;
height:100px;
}
</style>
</head>
<body>
<div class = "mydiv">
This is a SQUARE
</div>
<input id = "hide" type = "button" value = "Hide" />
<input id = "show" type = "button" value = "Show" />
</body>
</html>
这将生成以下结果:
This will produce following result −
Toggling the Elements
jQuery 提供方法用来切换元素的显示状态,使其在显示或隐藏之间切换。如果元素最初显示,那么会被隐藏;如果隐藏,那么会被显示。
jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown.
Syntax
以下是其中一个 toggle() 方法的简单语法 −
Here is the simple syntax for one of the toggle() methods −
[selector]..toggle([speed][, callback]);
以下是所有参数的说明 −
Here is the description of all the parameters −
-
speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
-
callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.
Example
<font color=red>我们可以对任何元素进行动画,例如包含一个图像的 simple <div> −</font>
We can animate any element, such as a simple <div> containing an image −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$(".clickme").click(function(event){
$(".target").toggle('slow', function(){
$(".log").text('Transition Complete');
});
});
});
</script>
<style>
.clickme{
margin:10px;
padding:12px;
border:2px solid #666;
width:100px;
height:50px;
}
</style>
</head>
<body>
<div class = "content">
<div class = "clickme">Click Me</div>
<div class = "target">
<img src = "./images/jquery.jpg" alt = "jQuery" />
</div>
<div class = "log"></div>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
JQuery Effect Methods
<font color=red>你已经看到 jQuery Effects 的基本概念。下表列出了所有用于创建不同效果类型的重要方法 −</font>
You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects −
Sr.No. |
Methods & Description |
1 |
animate( params, [duration, easing, callback] )A function for making custom animations. |
2 |
fadeIn( speed, [callback] )Fade in all matched elements by adjusting their opacity and firing an optional callback after completion. |
3 |
fadeOut( speed, [callback] )Fade out all matched elements by adjusting their opacity to 0, then setting display to "none" and firing an optional callback after completion. |
4 |
fadeTo( speed, opacity, callback )Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion. |
5 |
hide( )Hides each of the set of matched elements if they are shown. |
6 |
hide( speed, [callback] )Hide all matched elements using a graceful animation and firing an optional callback after completion. |
7 |
show( )Displays each of the set of matched elements if they are hidden. |
8 |
show( speed, [callback] )Show all matched elements using a graceful animation and firing an optional callback after completion. |
9 |
slideDown( speed, [callback] )Reveal all matched elements by adjusting their height and firing an optional callback after completion. |
10 |
slideToggle( speed, [callback] )Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion. |
11 |
slideUp( speed, [callback] )Hide all matched elements by adjusting their height and firing an optional callback after completion. |
12 |
stop( [clearQueue, gotoEnd ])Stops all the currently running animations on all the specified elements. |
13 |
toggle( )Toggle displaying each of the set of matched elements. |
14 |
toggle( speed, [callback] )Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion. |
15 |
toggle( switch )Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements). |
16 |
jQuery.fx.offGlobally disable all animations. |
UI Library Based Effects
<font color=red>要使用这些效果,你可以从 jQuery UI Library 下载最新的 jQuery UI 库 jquery-ui-1.11.4.custom.zip ,或者使用 Google CDN 以与我们对 jQuery 所做的类似方式来使用它。</font>
To use these effects you can either download latest jQuery UI Library jquery-ui-1.11.4.custom.zip from jQuery UI Library or use Google CDN to use it in the similar way as we have done for jQuery.
<font color=red>我们在 HTML 页面中使用以下代码片段为 jQuery UI 使用了 Google CDN,以便我们可以使用 jQuery UI −</font>
We have used Google CDN for jQuery UI using following code snippet in the HTML page so we can use jQuery UI −
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
</script>
</head>
Sr.No. |
Methods & Description |
1 |
BlindBlinds the element away or shows it by blinding it in. |
2 |
BounceBounces the element vertically or horizontally n-times. |
3 |
ClipClips the element on or off, vertically or horizontally. |
4 |
DropDrops the element away or shows it by dropping it in. |
5 |
ExplodeExplodes the element into multiple pieces. |
6 |
FoldFolds the element like a piece of paper. |
7 |
HighlightHighlights the background with a defined color. |
8 |
PuffScale and fade out animations create the puff effect. |
9 |
PulsatePulsates the opacity of the element multiple times. |
10 |
ScaleShrink or grow an element by a percentage factor. |
11 |
ShakeShakes the element vertically or horizontally n-times. |
12 |
SizeResize an element to a specified width and height. |
13 |
SlideSlides the element out of the viewport. |
14 |
TransferTransfers the outline of an element to another. |
jQuery - Interactions
Interactions could be added basic mouse-based behaviours to any element. Using with interactions, We can create sortable lists, resizeable elements, drag & drop behaviours.Interactions also make great building blocks for more complex widgets and applications.
Sr.No. |
Interactions & Description |
1 |
Drag ableEnable drag able functionality on any DOM element. |
2 |
Drop ableEnable any DOM element to be drop able. |
3 |
Resize ableEnable any DOM element to be resize-able. |
4 |
Select ableEnable a DOM element (or group of elements) to be selectable. |
5 |
Sort ableEnable a group of DOM elements to be sortable. |
jQuery - Widgets
一个 jQuery UI 部件是一个专门的 jQuery 插件。使用插件,我们可以为元素应用行为。但是,插件缺少某些内置功能,例如,将数据与其元素关联、公开方法、将选项与默认设置合并以及控制插件的生命周期。
a jQuery UI widget is a specialized jQuery plug-in.Using plug-in, we can apply behaviours to the elements. However, plug-ins lack some built-in capabilities, such as a way to associate data with its elements, expose methods, merge options with defaults, and control the plug-in’s lifetime.
Sr.No. |
Widgets & Description |
1 |
AccordionEnable to collapse the content, that is broken into logical sections. |
2 |
AutocompleteEnable to provides the suggestions while you type into the field. |
3 |
ButtonButton is an input of type submit and an anchor. |
4 |
DatepickerIt is to open an interactive calendar in a small overlay. |
5 |
DialogDialog boxes are one of the nice ways of presenting information on an HTML page. |
6 |
MenuMenu shows list of items. |
7 |
ProgressbarIt shows the progress information. |
8 |
Select menuEnable a style able select element/elements. |
9 |
SliderThe basic slider is horizontal and has a single handle that can be moved with the mouse or by using the arrow keys. |
10 |
SpinnerIt provides a quick way to select one value from a set. |
11 |
TabsIt is used to swap between content that is broken into logical sections. |
12 |
TooltipIts provides the tips for the users. |
jQuery - Theming
Jquery 具有两种不同的样式主题:A 和 B。每个主题针对按钮、栏、内容块等具有不同的颜色。
Jquery has two different styling themes as A And B.Each with different colors for buttons, bars, content blocks, and so on.
J query 主题语法如下 −
The syntax of J query theming as shown below −
<div data-role = "page" data-theme = "a|b">
一个简单的 A 主题化示例如下所示 −
A Simple of A theming Example as shown below −
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet"
href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script
src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
</script>
</head>
<body>
<div data-role = "page" id = "pageone" data-theme = "a">
<div data-role = "header">
<h1>Tutorials Point</h1>
</div>
<div data-role = "main" class = "ui-content">
<p>Text link</p>
<a href = "#">A Standard Text Link</a>
<a href = "#" class = "ui-btn">Link Button</a>
<p>A List View:</p>
<ul data-role = "listview" data-autodividers = "true" data-inset = "true">
<li><a href = "#">Android </a></li>
<li><a href = "#">IOS</a></li>
</ul>
<label for = "fullname">Input Field:</label>
<input type = "text" name = "fullname" id = "fullname"
placeholder = "Name..">
<label for = "switch">Toggle Switch:</label>
<select name = "switch" id = "switch" data-role = "slider">
<option value = "on">On</option>
<option value = "off" selected>Off</option>
</select>
</div>
<div data-role = "footer">
<h1>Tutorials point</h1>
</div>
</div>
</body>
</html>
这将产生以下结果 −
This should produce following result −
一个简单的 B 主题化示例如下所示 −
A Simple of B theming Example as shown below −
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet"
href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script src = "https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script
src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
</script>
</head>
<body>
<div data-role = "page" id = "pageone" data-theme = "b">
<div data-role = "header">
<h1>Tutorials Point</h1>
</div>
<div data-role = "main" class = "ui-content">
<p>Text link</p>
<a href = "#">A Standard Text Link</a>
<a href = "#" class = "ui-btn">Link Button</a>
<p>A List View:</p>
<ul data-role = "listview" data-autodividers = "true" data-inset = "true">
<li><a href = "#">Android </a></li>
<li><a href = "#">IOS</a></li>
</ul>
<label for = "fullname">Input Field:</label>
<input type = "text" name = "fullname" id = "fullname"
placeholder = "Name..">
<label for = "switch">Toggle Switch:</label>
<select name = "switch" id = "switch" data-role = "slider">
<option value = "on">On</option>
<option value = "off" selected>Off</option>
</select>
</div>
<div data-role = "footer">
<h1>Tutorials point</h1>
</div>
</div>
</body>
</html>
这将产生以下结果 −
This should produce following result −
jQuery - Utilities
Jquery 提供了一些 $(name space) 格式的实用程序。这些方法有助于完成编程任务。下面展示其中几个实用程序方法。
Jquery provides serveral utilities in the formate of $(name space). These methods are helpful to complete the programming tasks.a few of the utility methods are as show below.
$.trim()
$.trim() 用于移除前导和尾随空白
$.trim() is used to Removes leading and trailing whitespace
$.trim( " lots of extra whitespace " );
$.each()
$.each() 用于迭代数组和对象
$.each() is used to Iterates over arrays and objects
$.each([ "foo", "bar", "baz" ], function( idx, val ) {
console.log( "element " + idx + " is " + val );
});
$.each({ foo: "bar", baz: "bim" }, function( k, v ) {
console.log( k + " : " + v );
});
$.inArray()
$.inArray() 用于返回某个值在数组中的索引,如果数组中不存在该值,则返回 -1。
$.inArray() is used to Returns a value’s index in an array, or -1 if the value is not in the array.
var myArray = [ 1, 2, 3, 5 ];
if ( $.inArray( 4, myArray ) !== -1 ) {
console.log( "found it!" );
}
$.extend()
$.extend() 用于使用后续对象的属性更改第一个对象的属性。
$.extend() is used to Changes the properties of the first object using the properties of subsequent objects.
var firstObject = { foo: "bar", a: "b" };
var secondObject = { foo: "baz" };
var newObject = $.extend( firstObject, secondObject );
console.log( firstObject.foo );
console.log( newObject.foo );
$.proxy()
$.proxy() 用于返回一个总是在给定范围中运行的函数——即,将传入函数中的 this 的含义设置为第二个参数
$.proxy() is used to Returns a function that will always run in the provided scope — that is, sets the meaning of this inside the passed function to the second argument
var myFunction = function() {
console.log( this );
};
var myObject = {
foo: "bar"
};
myFunction(); // window
var myProxyFunction = $.proxy( myFunction, myObject );
myProxyFunction();
$.browser
$.browser 用于提供浏览器信息
$.browser is used to give the information about browsers
jQuery.each( jQuery.browser, function( i, val ) {
$( "<div>" + i + " : <span>" + val + "</span>" )
.appendTo( document.body );
});
$.contains()
$.contains() 用于判断由第二个参数提供的 DOM 元素是否是直接后代还是更深层嵌套后代的第一个参数提供的 DOM 元素的子级,返回 true。
$.contains() is used to returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply.
$.contains( document.documentElement, document.body );
$.contains( document.body, document.documentElement );
$.data()
$.data() 用于提供数据信息
$.data() is used to give the information about data
<html lang = "en">
<head>
<title>jQuery.data demo</title>
<script src = "https://code.jquery.com/jquery-1.10.2.js">
</script>
</head>
<body>
<div>
The values stored were <span></span>
and <span></span>
</div>
<script>
var div = $( "div" )[ 0 ];
jQuery.data( div, "test", {
first: 25,
last: "tutorials"
});
$( "span:first" ).text( jQuery.data( div, "test" ).first );
$( "span:last" ).text( jQuery.data( div, "test" ).last );
</script>
</body>
</html>
输出如下
An output would be as follows
The values stored were 25 and tutorials
$.fn.extend()
$.fn.extend() 用于扩展 jQuery 原型
$.fn.extend() is used to extends the jQuery prototype
<html lang = "en">
<head>
<script src = "https://code.jquery.com/jquery-1.10.2.js">
</script>
</head>
<body>
<label><input type = "checkbox" name = "android">
Android</label>
<label><input type = "checkbox" name = "ios"> IOS</label>
<script>
jQuery.fn.extend({
check: function() {
return this.each(function() {
this.checked = true;
});
},
uncheck: function() {
return this.each(function() {
this.checked = false;
});
}
});
// Use the newly created .check() method
$( "input[type = 'checkbox']" ).check();
</script>
</body>
</html>
它提供以下所示的输出 −
It provides the output as shown below −
$.isWindow()
$.isWindow() 用于识别窗口
$.isWindow() is used to recognise the window
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery.isWindow demo</title>
<script src = "https://code.jquery.com/jquery-1.10.2.js">
</script>
</head>
<body>
Is 'window' a window? <b></b>
<script>
$( "b" ).append( "" + $.isWindow( window ) );
</script>
</body>
</html>
它提供以下所示的输出 −
It provides the output as shown below −
$.now()
它返回一个代表当前时间数字
It returns a number which is representing the current time
(new Date).getTime()
$.isXMLDoc()
$.isXMLDoc() 检查文件是否是 xml
$.isXMLDoc() checks whether a file is an xml or not
jQuery.isXMLDoc( document )
jQuery.isXMLDoc( document.body )
$.globalEval()
$.globalEval() 用于全局执行 javascript
$.globalEval() is used to execute the javascript globally
function test() {
jQuery.globalEval( "var newVar = true;" )
}
test();
$.dequeue()
$.dequeue() 用于执行队列中的下一个函数
$.dequeue() is used to execute the next function in the queue
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery.dequeue demo</title>
<style>
div {
margin: 3px;
width: 50px;
position: absolute;
height: 50px;
left: 10px;
top: 30px;
background-color: green;
border-radius: 50px;
}
div.red {
background-color: blue;
}
</style>
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button>Start</button>
<div></div>
<script>
$( "button" ).click(function() {
$( "div" )
.animate({ left: '+ = 400px' }, 2000 )
.animate({ top: '0px' }, 600 )
.queue(function() {
$( this ).toggleClass( "red" );
$.dequeue( this );
})
.animate({ left:'10px', top:'30px' }, 700 );
});
</script>
</body>
</html>
它提供以下所示的输出 −
It provides the output as shown below −