Common methods of jQuery


<c:set var="ctx" value="${pageContext.request.contextPath}" />

<script type="text/javascript" >
function ctx(){
	return '${ctx}';



0. Commonly used codes:


Please allow me to insert a 0 before the 1. I think it is necessary for me to put the most commonly used codes first. After all, most of the time everyone is looking for codes.

(1)AJAX request

				async:true,the//The default is set to true, all requests are asynchronous.
					username:the $("#username").val()
				contentType: "application/json",
				success:the function(data)the{
				username:the $("#username").val(),
				content:the $("#content").val()
			success:the function(data)the{

(2) How to get the checkbox and determine whether it is selected

//Return result: selected=true, unselected=false

(3) Get the value selected by the checkbox

var chk_value =[]; 

(4)checkbox select all / reverse selection / select odd number

$("document").ready(function() {
	$("#btn1").click(function() {
		$("[name='checkbox']").attr("checked", 'true'); //select all  
	}) $("#btn2").click(function() {
		$("[name='checkbox']").removeAttr("checked"); //unselect all
	}) $("#btn3").click(function() {
		$("[name='checkbox']:even").attr("checked", 'true'); //Select all odd numbers
	}) $("#btn4").click(function() {
		$("[name='checkbox']").each(function() { //Anti-election
			if ($(this).attr("checked")) {
			} else {
				$(this).attr("checked", 'true');

(5) Get the value of the select drop-down box

In fact, the drop-down box is the simplest, just val


(6) To get the selected value, three methods are available:


(7) Set the first Radio as the selected value:

$('input:radio:first').attr('checked', 'checked');


$('input:radio:first').attr('checked', 'true');

(8) Set the last Radio as the selected value:

$('input:radio:last').attr('checked', 'checked');


$('input:radio:last').attr('checked', 'true');

(9) Set any radio as the selected value according to the index value:

$('input:radio').eq(index value).attr('checked', 'true');//index value=0,1,2....


$('input:radio').slice(1,2).attr('checked', 'true');

(10) Set Radio as the selected value according to the Value value




1. References to page elements

Reference elements through jquery's $() include methods such as id, class, element name, element hierarchy, dom or xpath conditions, and the returned object is a jquery object (collection object), and the method defined by dom cannot be called directly.


2. Conversion between jQuery object and dom object

Only jquery objects can use the methods defined by jquery. Note that there is a difference between a dom object and a jquery object. When calling a method, pay attention to whether the operation is a dom object or a jquery object.

Ordinary dom objects can generally be converted into jquery objects through $().  



It is a jquery object, you can use the jquery method.

Since the jquery object itself is a collection. So if the jquery object is to be converted into a dom object, one of the items must be taken out, which can usually be taken out by index.



These are dom objects, you can use methods in dom, but you can no longer use Jquery methods.  

The following spellings are all correct:



3. How to get an item of jQuery collection

For the retrieved element set, one of the items (specified by the index) can be obtained by using the eq or get(n) method or the index number. It should be noted that eq returns the jquery object, while get(n) and the index return Is the dom element object. For jquery objects, only jquery methods can be used, while dom objects can only use dom methods, such as getting the content of the third <div> element. There are two methods:

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


4. The same function implements set and get

Many methods in Jquery are like this, mainly including the following:

$("#msg").html(); // Return the html content of the element node whose id is msg.
$("#msg").html("<b>new content</b>");
//Write "<b>new content</b>" as an html string into the content of the element node whose id is msg, and the page displays bold new content
$("#msg").text(); // Return the text content of the element node whose id is msg.
$("#msg").text("<b>new content</b>");
//Write "<b>new content</b>" as a normal text string into the content of the element node whose id is msg, and the page displays <b>new content</b>
$("#msg").height(); //Returns the height of the element whose id is msg
$("#msg").height("300"); //Set the height of the element whose id is msg to 300
$("#msg").width(); //Returns 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("); //Returns 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 whose id is msg
$("#msg").click(fn); //Add a function for the click event of the element whose id is msg

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


5. Collection processing function

For the collection content returned by jquery, we don't need to loop through it ourselves and process each object separately. jquery has provided us with a very convenient method to process the collection.

Includes two forms:

//Set different font colors for the p elements whose indexes are 0, 1, and 2 respectively.
//Realize the interlaced color change effect of the table
//A click event is added for each p element, and its content pops up when a p element is clicked


6. Expand the functions we need

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

Using the extended method (called via "$.methodname"):



7. Support method continuous writing

The so-called continuous writing means that various methods can be continuously called on a jquery object.  

For example: 

.mouseover(function(){alert('mouse over event')})


8. The style of the operation element

It mainly includes the following methods:

$("#msg").css("background"); //Returns 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 the style in the form of name-value pairs
$("#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 named select


9. Perfect event processing function

Jquery has provided us with various event handling methods. Instead of directly writing events on html elements, we can directly add events to objects obtained through jquery.


$("#msg").click(function(){alert("good")}) //Added a click event to the element
//Set different processing for three different p element click events

Several custom events in jQuery:

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

//Set the class to over when the mouse is placed on a row of the table, and set it to out when it leaves.



(2) ready(fn): Bind a function to be executed when the DOM is ready for query and manipulation.  

$(document).ready(function(){alert("Load Success")}) 

//Prompt "Load Success" when the page is loaded. Unlike 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 every time it is clicked. If a matching element is clicked, the specified first function is triggered, and when the same element is clicked again, the specified second function is triggered. Each subsequent click repeats the alternate calls to these two functions.  

//Alternately add and remove the class named selected every time it is clicked.

(4) trigger(eventtype): Trigger a certain type of event on each matched element.

For example:

$("p").trigger("click"); //trigger the click event of all p elements

(5) bind(eventtype,fn), unbind(eventtype): event binding and anti-binding

(Add) removes the bound event from each matched element.  

For example:  

$("p").bind("click", function(){alert($(this).text());}); //add click event for each p element

$("p").unbind(); //Delete all events on all p elements

$("p").unbind("click") //Remove the click event on all p elements


10. Several practical special effects functions

The toggle() and slidetoggle() methods provide the state switching function.  

For example, the toggle() method includes the hide() and show() methods.  

The slideToggle() method includes the slideDown() and slideUp methods.


11. Several useful jQuery methods

$.browser.BrowserType: Detect browser type. Valid parameters: safari, opera, msie, mozilla. If it detects whether it is ie: $.browser.isie, it returns true if it is ie browser.  

$.each(obj, fn): general iteration function. Can be used to approximate objects and arrays (instead of loops).  


$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });

Equivalent to:  

var tempArr=[0,1,2]; 
for(var i=0;i<tempArr.length;i++){ 
    alert("Item #"+i+": "+tempArr[i]); 


Can also handle 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 one or more other Object to extend an object and return the extended object. This is how jquery implements inheritance.  


$.extend(settings, options);

//Merge settings and options, and return the merged result to settings, which is equivalent to options inheriting setting and saving the inheritance result in setting.  

var settings = $.extend({}, defaults, options);

//Merge defaults and options, and return the merged result to setting without overwriting the default content.  

There can be multiple parameters (merge multiple items and return)

$.map(array, fn): Array mapping. Save the items in one array (after processing transformations) into another new array, and return the resulting new array.  


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.  


$.merge( [0,1,2], [2,3,4] ) //returns [0,1,2,3,4]

$.trim(str): Remove whitespace characters at both ends of the string.  


$.trim(" hello, how are you? "); //returns "hello,how are you?"


12. Solve custom methods or other The conflict between the class library and jQuery

Many times we define the $(id) method to get an element, or other Some js libraries such as prototype also define the $ method. If these contents are put together at the same time, it will cause conflicts in the definition of variable methods. Jquery specifically provides methods to solve this problem.  

Use the jQuery.noConflict(); method in jquery to transfer the control of the variable $ to the first library that implements it or the previously customized $ method. When using Jquery later, you only need to replace all $ with jQuery, such as the original reference object method $("#msg") to jQuery("#msg").  


//Get started with jQuery
jQuery("div p").hide(); 
//  use other Library $() 
$("content").style.display = 'none';other Library $() 
$("content").style.display = 'none';


Tags: JQuery

Posted by met0555 on Mon, 06 Feb 2023 21:11:54 +1030