search
HomeWeb Front-endJS TutorialjQuery Skills Collection (Introduction to Beginners)_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 There 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 complicated JS applications and turn their attention to 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:
1. Concise code, easy-to-understand semantics, fast learning, and rich documentation.
2. jQuery is a lightweight script, and its code is very small. The latest version of the JavaScript package is only about 20K.
3. jQuery supports CSS1-CSS3, as well as basic xPath.
4. jQuery is cross-browser, and the browsers it supports include IE 6.0, FF 1.5, Safari 2.0, Opera 9.0.
5. It is easy to extend other functions for jQuery.
6. JS code and HTML code can be completely separated, making it easier to code, maintain and modify.
7. Plug-ins are abundant. In addition to some special effects of jQuery itself, more functions can be realized through plug-ins, such as form validation, tab navigation, drag-and-drop effect, table sorting, DataGrid, tree menu, image special effects and 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, you can have a simple understanding of jQuery, understand the difference between JQuery and other JS frameworks, and master the common syntax and usage of jQuery Tips and precautions.

2. How to use
Just introduce the JQuery js file into the page where JQuery is needed.
For example:
After
is 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

Recommend two good jquery tutorials: "jQuery Starting Tutorial" and "Using jQuery to Simplify Ajax Development" (Note: The above documents are placed in [Attachment]
Medium)
4. Syntax summary and precautions

1. References about page elements

Referencing elements through jquery’s $() includes methods such as id, class, element name, hierarchical relationship of elements, dom or xpath conditions, etc., and the returned object is a jquery object (collection object), and dom cannot be called directly defined method.
2. Conversion between 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:
$("#msg").html();
$("#msg")[0].innerHTML;
$("# msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;
3. How to get a certain item in the jQuery collection Item
For the obtained set of elements, obtaining an item (specified by index) can be obtained using the eq or get(n) method or the index number. It should be noted 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, if you want to get the content of the third element.There are the following two methods:
$("div").eq(2).html();                                                                                   using using using using  -                                                                                                                                                     / /Call dom method attributes


4. The same function implements set and getThis is true for many methods in Jquery, mainly including the following:
$(" #msg").html(); //Return the html content of the element node with id msg.
$("#msg").html("
new content"); //Write "
new content" as an html string with the id msg In the element node content, the page displays bold new content
$("#msg").text(); //Returns the text content of the element node with the id msg.
$("#msg").text("
new content"); //Write "
new content" as a normal text string with id msg In the element node content, the page displays new content
$("#msg").height();                                                                                                                                                                                                                                       . #msg").height("300"); //Set the height of the element with id msg to 300
$("#msg").width(); //Return the width of the element with id msg
$("#msg").width("300"); //Set the width of the element with id 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 of the element with id msg
$("#msg").click(fn); //Add a function for the click event of the element with id msg
Similarly blur, focus, select, and submit events can all have two calling methods


5. Collection processing function
For the collection content returned by jquery, we do not need to loop through it ourselves and process each The objects are processed separately, and jquery has provided us with a very convenient method for processing collections. includes two forms:
$("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())})                                                                                  Click on a p element and its content will pop up


6. Extend the functions we need

$.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 via "$.method name"): alert("a=10,b=20,max=" $.max(10,20) ",min=" $. min(10,20));


7. Support method concatenation

The so-called concatenation means that you can continuously call various methods on a jquery object. For example: $("p").click(function(){alert($(this).html())})
.mouseover(function(){alert('mouse over event ')})
.each(function(i){this.style.color=['#f00','#0f0','#00f'][i]});


8. Manipulating the style of elements

mainly includes the following methods: $("#msg").css("background"); ("#msg").css("background","#ccc") //Set the background of the element to gray$("#msg").height(300); $("#msg"). width("200"); //Set width and height
$("#msg").css({ color: "red", background: "blue" });//Set in the form of name-value pairs Define the style
$("#msg").addClass("select"); //Add a class named select to the element
$("#msg").removeClass("select"); // Delete the class whose element name is select
$("#msg").toggleClass("select"); //If it exists (does not exist), delete (add) the class whose name is 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 add events to objects obtained through jquery.
For example: $("#msg").click(function(){alert("good")}) //Add a click event to the element$("p").click (function(i){this.style.color=['#f00','#0f0','#00f'][i]})
//Set three different p element click events respectively Different handling

Several custom events in jQuery:

(1)
hover(fn1,fn2): A simulated hover event (the mouse moves to methods on and out of an 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.
//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");
},
                                        .addClass("out");
});
(2)
ready(fn):Bind a function to be executed when the DOM is loaded and ready for query and manipulation. $(document).ready(function(){alert("Load Success")})
//When the page is loaded, it prompts "Load Success". Different from the onload event, onload requires that the page content has been loaded (picture etc.), and ready is triggered as soon as the page html code is downloaded. Equivalent to $(fn)
(3)
toggle(evenFn,oddFn): Toggle 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. //Add and delete the class named selected in rotation every time you click.
$("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:
$("p").bind("click", function(){alert($(this).text());}); //Add click for each p element Event
$("p").unbind(); //Delete all events on all p elements
$("p").unbind("click") //Delete all single events on all p elements Click event


10. Several practical special effects functions Among them, 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). For example,
$.each( [0,1,2], function(i, n){ alert( "Item #" i ": " n ); });
is equivalent to:
var tempArr=[0,1,2];
for(var i=0;i alert("Item #" i ": " tempArr[i]) ;}
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): 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 items 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; });
tempArr content 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 of custom methods or other class libraries Conflicts with jQueryMany 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:
jQuery.noConflict();
// Start using jQuery
jQuery("div p").hide();
// Use $() from other libraries
$("content").style.display = 'none';
Attachment
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools