Home Web Front-end JS Tutorial Sharing 12 common tips for jQuery_jquery

Sharing 12 common tips for jQuery_jquery

May 16, 2016 pm 06:03 PM
jquery Commonly used techniques

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 a 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, 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 the dom method attribute
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 of 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 form input box value
$("input").val("test"); //Set the value of the form input box to test
$("#msg").click(); //Trigger id For the click event of the msg element
$("#msg").click(fn); //Add a function for the click event of the element with the id msg
The same blur, focus, select, and submit events are There are 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 object separately. jQuery has provided us with a lot of Convenient methods for processing collections, including 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 the interlaced color changing effect of the table
$("p").click( function(){alert($(this).html())})
//Added click event for each p element. Clicking on a p element will pop up its content
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 through "$.method name"):

01.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:

$("p").click(function(){alert($(this).html())})
.mouseover(function(){alert('mouse over event ')})
.each(function(i){this.style.color=['#f00','#0f0','#00f'][ i ]});
8 , operating the style of the element
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 simulated hover event (the mouse moves over an object and moves out of it) object) method. 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.

01.$(document).ready(function(){alert("Load Success")})
02.//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:

01.$("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

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

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

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; });
tempArr content 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 remove duplicate items.

For example:

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

$.trim(str): Remove blank characters at both ends of the string. Such as:

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

12. Solve custom methods or other Conflicts between class libraries and 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 also use Putting these contents together will cause variable method definition conflicts, and 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 a previously customized $ method. When using jQuery later, just replace all $ with jQuery. For example, the original referenced object method $("#msg") is changed to jQuery("#msg"). Such as:
jQuery.noConflict();
// Start using jQuery
jQuery("div p").hide();
// Use other libraries' $()
$ ("content").style.display = 'none';
Hope this is helpful to you.
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 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles