search
HomeWeb Front-endJS TutorialSummary of jQuery syntax and precautions_jquery

1. Introduction

1.1. Overview

With the rapid development and spread of WEB2.0 and ajax ideas on the Internet, some excellent Js frameworks have emerged one after another, among which the more famous ones are Prototype, YUI, jQuery, mootools, Bindows and domestic JSVM frameworks, etc., by applying these JS frameworks to our projects, programmers can be freed from designing and writing complex JS applications, and focus on functional requirements rather than implementation. details, thereby increasing the development speed of the project.

jQuery is another excellent Javascript framework after prototype. Created by John Resig in early 2006, it helps simplify JavaScript™ and Ajax programming. Some people use this metaphor to compare prototype and jQuery: prototype is like Java, and jQuery is like ruby. It is a simple, fast and flexible JavaScript framework that allows you to simply operate documents, handle events, and Implement special effects and add Ajax interaction to web pages.

It has the following characteristics:

Concise code, easy-to-understand semantics, fast learning, and rich documentation.
jQuery is a lightweight script, and its code is very small. The latest version of the JavaScript package is only about 20K.
jQuery supports CSS1-CSS3, as well as basic xPath.
jQuery is cross-browser, and the browsers it supports include IE 6.0, FF 1.5, Safari 2.0, Opera 9.0.
It is easy to extend other functions for jQuery.
It can completely separate JS code and HTML code, making it easier to code, maintain and modify.
Plug-ins are abundant. In addition to some special effects provided by jQuery itself, more functions can be implemented through plug-ins, such as form validation, tab navigation, drag-and-drop effects, table sorting, DataGrid, tree menu, image special effects, ajax upload, etc. .

The design of jQuery will change the way you write JavaScript code, reduce the complexity of learning to use JS to operate web pages, and improve the efficiency of web JS development. Whether you are a js beginner or a senior expert, jQuery will be your best choice First choice.

jQuery is suitable for designers, developers and those who are lucky, and is also suitable for commercial development. It can be said that jQuery is suitable for any JavaScript application and can be used in different web applications.

Official site: http://jquery.com/ Chinese site: http://jquery.org.cn/

1.2. Purpose

By studying this document, Be able to have a simple understanding of jQuery, understand the difference between JQuery and other JS frameworks, and master the common syntax, usage skills and precautions of jQuery.

2. How to use it

Introduce the js file of JQuery into the page that needs to use JQuery.
For example:
After being introduced, the syntax provided by jQuery can be used anywhere on the page.

3. Learning tutorials and reference materials

Please refer to the "jQuery Chinese API Manual" and http://jquery.org.cn/visual/cn/index. xml
recommends two good jquery tutorials: "jQuery Starting Tutorial" and "Using jQuery to Simplify Ajax Development"

4. Grammar Summary and Notes

1. References about page elements

Referencing elements through jquery’s $() includes id, class, element name, hierarchical relationship of elements and dom or xpath conditions and other methods, and the returned object is a jquery object (collection object), the method defined by dom cannot be directly called.

2. Conversion of jQuery objects and dom objects

Only jquery objects can use the methods defined by jquery. Note that there is a difference between dom objects and jquery objects. When calling methods, you should pay attention to whether you are operating on dom objects or jquery objects.
Ordinary dom objects can generally be converted into jquery objects through $().
For example: $(document.getElementById("msg")) is a jquery object, and you can use jquery methods.
Because the jquery object itself is a collection. Therefore, if the jquery object is to be converted into a dom object, one of the items must be retrieved, which can generally be retrieved through an index.
For example: $("#msg")[0], $("div").eq(1)[0], $("div").get()[1], $("td" )[5] These are dom objects, you can use methods in dom, but you can no longer use Jquery methods.
The following writing methods are correct:

Copy code The code is as follows:

$("#msg").html();
$("#msg")[0].innerHTML;
$("#msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;

3. How to get an item of jQuery collection

For the obtained element collection, to get an item (specified by index), you can use eq or get(n) Method or index number is obtained. Please note that eq returns a jquery object, while get(n) and index return a dom element object. For jquery objects, you can only use jquery methods, and for dom objects, you can only use dom methods. For example, you want to get the content of the third
element. There are two methods:
Copy code The code is as follows:

$("div") .eq(2).html(); //Call the method of jquery object
$("div").get(2).innerHTML; //Call the method of dom attribute


4. The same function implements set and get

Many methods in Jquery are like this, mainly including the following:
Copy code The code is as follows:

$("#msg").html(); //Return the html content of the element node with id msg .
$("#msg").html("new content");
//Write "new content" as an html string In the content of the element node with the id of msg, the page displays bold new content

$("#msg").text(); //Return the text content of the element node with the id of msg.
$("#msg").text("new content");
//Write "new content" as a normal text string Enter the element node content with id msg, and the page displays new content

$("#msg").height(); //Return the height of the element with id msg
$("#msg").height("300"); //Set the height of the element with id msg to 300
$("#msg").width(); //Return id The width of the element whose id is msg
$("#msg").width("300"); //Set the width of the element whose id is msg to 300

$("input"). val("); //Return the value of the form input box
$("input").val("test"); //Set the value of the form input box to test

$ ("#msg").click(); //Trigger the click event for the element with id msg
$("#msg").click(fn); //Click event for the element with id msg Add function



Similarly blur, focus, select, submit events can have these two calling methods

5. Collection processing function

For the collection contents returned by jquery, we do not need to loop through and process each object separately. jquery has provided us with a very convenient method to process the collection.
Including two forms:

6. Expand the functions we need
Copy the code The code is as follows:

$.extend({
min: function(a, b){return a max: function(a, b){return a > b?a:b; }
}); //Extended min and max methods for jquery

Use the extended method (called through "$.method name") :

alert("a=10,b=20,max=" $.max(10,20) ",min=" $.min(10,20));

7. Supports continuous writing of methods
The so-called continuous writing means that you can continuously call various methods on a jquery object.

For example:
Copy code The code is as follows:

$("p ").click(function(){alert($(this).html())})
.mouseover(function(){alert('mouse over event')})
.each(function( i){this.style.color=['#f00','#0f0','#00f'][i]});

8. Style of operating elements

Mainly include the following methods:
Copy code The code is as follows:

$("#msg").css("background"); //Return the background color of the element
$("#msg").css("background","#ccc") //Set Set the background of the element to gray
$("#msg").height(300); $("#msg").width("200"); //Set the width and height
$("#msg ").css({ color: "red", background: "blue" });//Set styles in the form of name-value pairs
$("#msg").addClass("select"); / /Add a class named select to the element
$("#msg").removeClass("select"); //Remove the class named select for the element
$("#msg").toggleClass(" select"); //If it exists (does not exist), delete (add) the class named select

9. Complete event processing function

Jquery has provided us with various event processing methods. We do not need to write events directly on html elements, but can directly process them through jquery The obtained object adds an event.
For example:
Copy code The code is as follows:

$("#msg") .click(function(){alert("good")}) //Added a click event for the element
$("p").click(function(i){this.style.color=['# f00','#0f0','#00f'][i]}) //Set different processing for three different p element click events

Several customizations in jQuery Defined events:

(1) hover(fn1,fn2): A method that simulates hover events (the mouse moves over an object and out of the object). When the mouse moves over a matching element, the first specified function will be triggered. When the mouse moves out of this element, the specified second function will be triggered.
Copy code The code is as follows:

//When the mouse is placed on a row of the table Set the class to over and set it to out when leaving.
$("tr").hover(function(){
$(this).addClass("over");
},
function(){
$(this) .addClass("out");
});

(2) ready(fn): Bind a function to be executed when the DOM is loaded and ready for query and manipulation.
Copy code The code is as follows:

$(document).ready(function(){alert ("Load Success")})
//When the page is loaded, it prompts "Load Success". Different from the onload event, onload requires the page content to be loaded (pictures, etc.), while ready is triggered as long as the page html code is downloaded. Equivalent to $(fn)


(3) toggle(evenFn,oddFn): Switch the function to be called each time it is clicked. If a matching element is clicked, the first function specified is triggered, and when the same element is clicked again, the second function specified is triggered. Each subsequent click repeats the call to these two functions in turn.
Copy code The code is as follows:

//Every time you click, add and delete named names in rotation selected class.
$("p").toggle(function(){
$(this).addClass("selected");
},function(){
$(this).removeClass( "selected");
});

(4) trigger(eventtype): Trigger a certain type of event on each matching element.
For example:
$("p").trigger("click"); //Trigger click events for all p elements

(5) bind(eventtype,fn), unbind(eventtype ): Binding and unbinding of events
Remove (add) the bound event from each matching element.
For example:
Copy code The code is as follows:

$("p"). bind("click", function(){alert($(this).text());});
//Add a click event for each p element
$("p").unbind (); //Delete all events on all p elements
$("p").unbind("click") //Delete all click events on all p elements



10. Several practical special effects functions

The toggle() and slidetoggle() methods provide state switching functions.
For example, the toggle() method includes hide() and show() methods.
The slideToggle() method includes the slideDown() and slideUp methods.

11. Several useful jQuery methods

$.browser. Browser type: Detect browser type. Valid parameters: safari, opera, msie, mozilla. For example, if you check whether it is IE: $.browser.isie, if it is an IE browser, it will return true.
$.each(obj, fn): General iteration function. Can be used to iterate over objects and arrays approximately (instead of looping).
Such as
$.each( [0,1,2], function(i, n){ alert( "Item #" i ": " n ); });

Equivalent In:
Copy code The code is as follows:

var tempArr=[0,1,2] ;
for(var i=0;ialert("Item #" i ": " tempArr[i]);
}

You can also process json data, such as
$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " i ", Value: " n ); });

The result is:
Name:name, Value:John
Name:lang, Value:JS
$.extend(target,prop1,propN): Use Extend an object with one or more other objects and return the extended object. This is the inheritance method implemented by jquery.
For example:
$.extend(settings, options);
//Merge settings and options, and return the merged result to settings, which is equivalent to options inheriting setting and saving the inherited result in setting.
var settings = $.extend({}, defaults, options);
//Merge defaults and options, and return the merged result to the setting without overwriting the default content.
Can have multiple parameters (combine multiple parameters and return)

$.map(array, fn): array mapping. Saves the items in an array (after processing the transformation) into a new array and returns the resulting new array.
For example:
var tempArr=$.map( [0,1,2], function(i){ return i 4; });
The content of tempArr is: [4,5,6]
var tempArr=$.map( [0,1,2], function(i){ return i > 0 ? i 1 : null; });
The content of tempArr is: [2,3]
$.merge(arr1,arr2): Merge two arrays and delete duplicate items.
For example:
$.merge( [0,1,2], [2,3,4] ) //Return [0,1,2,3,4]

$. trim(str): Remove whitespace characters at both ends of the string.
For example:
$.trim(" hello, how are you? "); //Return "hello, how are you? "

12. Solve the problem with custom methods or other class libraries Conflicts with jQuery

Many times we define the $(id) method ourselves to get an element, or some other js libraries such as prototype also define the $method. If we put these contents together at the same time, Will cause variable method definition conflict, Jquery provides a special method to solve this problem.
Use the jQuery.noConflict(); method in jquery to transfer control of the variable $ to the first library that implements it or the previously customized $ method. When using Jquery later, just replace all $ with jQuery. For example, the original reference object method $("#msg") is changed to jQuery("#msg").
For example:
Copy code The code is as follows:

jQuery.noConflict();
// Start using jQuery
jQuery("div p").hide();
// Use other libraries' $()
$("content").style.display = 'none ';
$("p").each(function(i){this.style.color=['#f00','#0f0','#00f'][i]})
/ / Set different font colors for the p elements with indexes 0, 1, and 2 respectively.
$("tr").each(function(i){this.style.backgroundColor=['#ccc','#fff'][i%2]})
//Achieve alternate rows in the table Color changing effect
$("p").click(function(){alert($(this).html())})
//Added click event for each p element, click on a certain If a p element is used, its content
will pop up
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.