Home  >  Article  >  Web Front-end  >  jquery common skills and common methods list collection_jquery

jquery common skills and common methods list collection_jquery

WBOY
WBOYOriginal
2016-05-16 18:08:33859browse
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