search
HomeWeb Front-endJS Tutorialjquery common skills and common methods list collection_jquery

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 ways of writing are all correct:
3. How to get a certain item of the jQuery collection
For the obtained element collection, get a certain item (specified by index ) can be obtained using the eq or get(n) method or the index number. 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, 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.
//Write "new content" as an HTML string into the element node content with the id msg, and the page will display bold new content
$("#msg").text(); //Return the id It is the text content of the element node of msg.
//Write "new content" as a normal text string into the content of the element node with the id of msg, and the page displays new content
$("#msg").height(); //Return the id of msg The height of the element
$("#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 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 Each object is processed separately. jquery has provided us with a very convenient method to process collections.
includes two forms:
//Set different values ​​for the p elements with indexes of 0, 1, and 2 respectively.
//Achieve the interlaced color changing effect of the table
//Add a click event for each p element, and click on a p element to pop up its content
6. Extension The functions we need
}); //Extended min and max methods for jquery
Use the extended method (called through "$.method name"):
7 , support the concatenation of methods
The so-called concatenation means that you can continuously call various methods on a jquery object. For example:

8. The style of operating elements Mainly include 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 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 Various event handling methods have been provided for us. 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(){}) //Add a click event to the element
//Set separate click events for three different p elements 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.
(2) ready(fn): Bind a function to be executed when the DOM is loaded and ready for query and manipulation.
//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.
(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(){.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
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,
is equivalent to:
can also process json data, such as
and the result is:
$.extend(target,prop1,propN): Extend with one or more other objects An object that returns the expanded object. This is the inheritance method implemented by jquery.
For example:
//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.
//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:
The content of tempArr is: [4,5,6]
The content of tempArr is: [2,3]
$.merge(arr1, arr2): Merge two arrays and delete them 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 conflicts between custom methods or other 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 these contents are put together at the same time, variables will be caused. 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 referenced object method $("#msg") is changed to jQuery("#msg").
For example:
// Start using jQuery
// Use $() from other libraries
List of common jquery methods:
Attribute:
$(p).addClass(css Defined style type); Add a style to an element
$(img).attr({src:test.jpg,alt:test Image}); Add an attribute/value to an element, the parameter is map
$(img).attr(src,test.jpg); Add attributes/values ​​to an element
$(img).attr(title, function() { return this.src }); Add attributes/value to an element Add attributes/values ​​
$(element name).html(); Get the content (element, text, etc.) within the element
$(element name).html(new stuff); Set content for an element
$(element name).removeAttr(attribute name) Delete the specified attribute and the value of the attribute from an element
$(element name).removeClass(class) Delete the specified style from an element
$( element name).text(); Get the text of the element
$(element name).text(value); Set the text value of the element to value
$(element name).toggleClass(class) When the element Cancel when the style in the parameter exists. If it does not exist, set this style
$(input element name).val(); Get the value of the input element
$(input element name).val(value); Set the value of the input element to value
Manipulation:
$(element name).after(content); Add content after the matching element
$(element name).append(content); Use content as an element The content is inserted after the element
$(element name).appendTo(content); The content is followed by the element
$(element name).before(content); The opposite of the after method
$( Element name).clone(Boolean expression) When the Boolean expression is true, clone the element (when there is no parameter, it is treated as true)
$(Element name).empty() Set the content of the element to empty
$(element name).insertAfter(content); Insert this element after content
$(element name).insertBefore(content); Insert this element before content
$(element). prepend(content); Use the content as part of the element and put it at the front of the element
$(element).prependTo(content); Use the element as a part of the content and put it at the front of the content
$ (Element).remove(); Delete all specified elements
$(Element).remove(exp); Delete all elements containing exp
$(Element).wrap(html); Surround the element with html Element
$(element).wrap(element); Use element to surround the element
Traversing:
Core:
$(html).appendTo(body) is equivalent to writing a paragraph in the body HTML code
$(elems) gets an element on the DOM
$(function(){..}); executes a function
$(div > p).css(border, 1px solid gray ); Find the child nodes p of all divs, add style
$(input:radio, document.forms[0]) Find all radio buttons in the first form of the current page
$.extend( prop) prop is a jquery object,
Example:
jQuery( expression, [context] ) $( expression, [context]); By default, $() queries the DOM in the current HTML document element.
each( callback ) uses each matched element as the context to execute a function
Example: 1
Example: 2
ready(fn); $(document).ready() Note in body There is no onload event, otherwise the function cannot be executed. In each page,
many functions can be loaded and executed, and they are executed in the order of fn.
bind( type, [data], fn ) binds one or more event handler functions to a specific event (like click) of each matching element. Possible event attributes are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove,
one( type, [data], fn ) is a specific event for each matching element ( Like click) bind one or more event handler functions. This event handler will only be executed once on each
object. Other rules are the same as bind() function.
trigger( type, [data] ) triggers a certain type of event on each matching element.
triggerHandler( type, [data] ) This specific method will trigger a specific event on an element (specify an event type) and cancel the browser's default action for this event.
unbind( [type], [ data] ) unbinding, removing the bound event from each matching element.
$(p).unbind() removes all bound events on all paragraphs
$(p).unbind( click ) removes click events on all paragraphs
hover( over, out ) over and out are both methods. 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.
toggle( fn, fn ) If a matching element is clicked, the specified first function is triggered. When the same element is clicked again, the specified second function is triggered.
Element event list description
Note: A function without parameters, its parameter is optional fn. jQuery does not support the reset event of the form element.
이벤트 설명은 요소 또는 객체를 지원합니다.
blur( ) 요소는 포커스를 잃습니다. a, input, textarea, 버튼, select, label, map, Area
change( ) 사용자가 필드 입력의 내용을 변경합니다. textarea, select
click( ) 객체의 거의 모든 요소를 ​​마우스로 클릭합니다.
dblclick( ) 객체의 거의 모든 요소를 ​​마우스로 더블클릭합니다.
error( ) 로드할 때 오류가 발생하는 경우 문서 또는 이미지 창, img
focus ( ) 요소가 포커스를 얻습니다 a, input, textarea, 버튼, 선택, 레이블, 지도, 영역
keydown( ) 특정 키보드 키를 눌렀을 때 거의 모든 요소
keypress ( ) 특정 키보드 키가 눌림 거의 모든 요소를 ​​누르거나 누르고 있음
keyup( ) 특정 키보드 키가 눌림 거의 모든 요소
load( fn ) 특정 페이지나 이미지가 로드된 창, img
mousedown( fn ) Some 거의 모든 요소에서 마우스 버튼을 눌렀습니다.
mousemove( fn ) 거의 모든 요소에서 마우스를 움직입니다.
mouseout( fn ) 거의 모든 요소에서 한 요소에서 마우스를 움직입니다.
mouseover( fn ) 요소 위에서 마우스가 이동합니다. 요소 위의 거의 모든 요소
mouseup( fn ) 마우스 버튼이 해제됩니다. 거의 모든 요소
resize( fn ) 창이나 프레임의 크기가 조정됩니다. window, iframe, Frame
스크롤( fn ) 문서 스크롤 보이는 부분이 창일 때
select( ) 텍스트가 선택됨 document, input, textarea
submit( ) submit 버튼 클릭 시
unload( fn ) 사용자가 페이지 창을 종료합니다.
JQuery Ajax 메서드 설명:
load( url, [data], [callback] )은 원격 HTML 콘텐츠를 DOM 노드에 로드합니다.
$(#feeds).load(feeds.html); 피드 ID를 사용하여 div에 Feeds.html 파일 로드
jQuery.get( url, [data], [callback] ) GET 요청 사용 페이지.
jQuery.getJSON( url, [data], [callback] )은 GET을 사용하여 JSON 데이터를 요청합니다.
jQuery.getScript( url, [callback] )는 GET을 사용하여 자바스크립트 파일을 요청하고 실행합니다.
jQuery.post( url, [data], [callback], [type] )은 POST를 사용하여 페이지를 요청합니다.
ajaxComplete( callback ) AJAX 요청이 끝나면 함수를 실행합니다. 이것은 Ajax 이벤트입니다.
ajaxError( callback ) AJAX 요청이 실패하면 함수를 실행합니다. 아약스 이벤트입니다
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: 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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.