Home Web Front-end JS Tutorial jQuery skills are given away. Friends who are learning jquery can take a look_jquery

jQuery skills are given away. Friends who are learning jquery can take a look_jquery

May 16, 2016 pm 06:44 PM
jquery Skill

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 jquery objects (collection objects) cannot directly call methods defined by dom.

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 element collection, to obtain an item (specified by index), you can use the eq or get(n) method or the index number. Note that eq returns a jquery object, and get (n) and index return the 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(); //Call the jquery object method
$("div").get(2).innerHTML; / /Call dom method attributes

4. The same function implements set and get
This 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(); //Returns 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 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())})
//Added click event for each p element, 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"); //Return the background color of the element
$ ("#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 with the element name select
$("#msg").toggleClass("select"); //If it exists (does not exist), delete (add) the class with the name 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")}) //Added 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 method that imitates hover events (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.
//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.
$(document).ready(function(){alert("Load Success")})
//When the page is loaded, it prompts "Load Success", which is equivalent to the onload event. Equivalent to $(fn)
(3) toggle(evenFn,oddFn): Switch the function to be called every 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.
//Rotate adding and deleting the class named selected 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 the click event of all p elements
(5) bind(eventtype,fn), unbind(eventtype): event Binding and unbinding
removes (adds) 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
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;ialert("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 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): Delete 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:
jQuery.noConflict();
// Start using jQuery
jQuery("div p").hide();
// Use $() from other libraries
$("content").style.display = 'none';
Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Mar 27, 2024 pm 02:57 PM

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

What are the tips for novices to create forms? What are the tips for novices to create forms? Mar 21, 2024 am 09:11 AM

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! Mar 26, 2024 am 08:21 AM

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

PHP programming skills: How to jump to the web page within 3 seconds PHP programming skills: How to jump to the web page within 3 seconds Mar 24, 2024 am 09:18 AM

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Win11 Tricks Revealed: How to Bypass Microsoft Account Login Win11 Tricks Revealed: How to Bypass Microsoft Account Login Mar 27, 2024 pm 07:57 PM

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

Tips for using Laravel form classes: ways to improve efficiency Tips for using Laravel form classes: ways to improve efficiency Mar 11, 2024 pm 12:51 PM

Forms are an integral part of writing a website or application. Laravel, as a popular PHP framework, provides rich and powerful form classes, making form processing easier and more efficient. This article will introduce some tips on using Laravel form classes to help you improve development efficiency. The following explains in detail through specific code examples. Creating a form To create a form in Laravel, you first need to write the corresponding HTML form in the view. When working with forms, you can use Laravel

Detailed explanation of the usage skills of √ symbol in word box Detailed explanation of the usage skills of √ symbol in word box Mar 25, 2024 pm 10:30 PM

Detailed explanation of the tips for using the √ symbol in the Word box. In daily work and study, we often need to use Word for document editing and typesetting. Among them, the √ symbol is a common symbol, which usually means "right". Using the √ symbol in the Word box can help us present information more clearly and improve the professionalism and beauty of the document. Next, we will introduce in detail the skills of using the √ symbol in the Word box, hoping to help everyone. 1. Insert the √ symbol In Word, there are many ways to insert the √ symbol. one

See all articles