Home >Web Front-end >JS Tutorial >Only after understanding these can you start to use the power of jQuery_jquery
由于当前jQuery如此的如雷贯耳,相信不用介绍什么是jQuery了,公司代码中广泛应用了jQuery,但我在看一些小朋友的代码时发现一个问题,小朋友们使用的仅仅是jQuery的皮毛,只是使用id选择器与attr方法,还有几个动画,如果只是如此,相比于其带来的开销,其实还不如不使用,下面介绍几个jQuery常用的方法,来让jQuery的威力发挥出来,否则只用有限的几个方法,相对于运行速度问题,真不如不用jQuery。
jQuery如此之好用,和其在获取对象时使用与CSS选择器兼容的语法有很大关系,毕竟CSS选择器大家都很熟悉(关于CSS选择器可以看看十分钟搞定CSS选择器),但其强大在兼容了CSS3的选择器,甚至多出了很多。
选择器
有了CSS选择器基础后,看jQuery的选择器就很简单了,不再详细一一说明
Basic Selector | ||
$(‘*’) | Match all elements on the page | |
$(‘#id’) | id selector | |
$(‘.class’) | Class selector | |
$(‘element’) | Tag Selector | |
Composition/Level Selector | ||
$(‘E,F’) | Multi-element selector, separated by ",, simultaneously matches element E or element F | |
$(‘E F’) | Descendant selector, separated by spaces, matches all descendants of the E element (not just sub-elements, sub-elements recursively downward) element F | |
$(E>F) | Child element selector, separated by ">", matches all direct child elements of the E element | |
$(‘E F’) | Directly adjacent selector, matches of after E element and sibling element F | |
Ordinary adjacent selector (younger brother selector), matches the | sibling element F of after E element (whether directly adjacent or not) | |
Match elements whose class name contains both class1 and class2 | ||
Basic Filter Selector | ||
The first of all E | ||
The last of all E | ||
Filter E by selector | ||
The index in all E is an even number | ||
The index in all E is an odd number | ||
$("E:gt(n)") | ||
$("E:ll(n)") | All elements in E with index less than n||
$(":header") | Select h1~h7 elements | |
$("div:animated") | Select the element that is performing the animation effect | |
Content Filter | ||
$(‘E:contains(value)’) | Elements whose content contains value | |
$(‘E:empty’) | Element with empty content | |
$(‘E:has(F)’) | Elements with F in their child elements, $('div:has(a)'): div | |
$(‘E: parent') | The parent element is the element of E, $('td: parent'): The parent element is the element of td | |
Visual Selector | ||
$(‘E:hidden’) | All hidden E | |
$(‘E:visible’) | All visible E | |
Attribute filter selector | ||
$(‘E[attr]') | 含有属性attr的E | |
$(‘E[attr=value]') | 属性attr=value的E | |
$(‘E[attr !=value]') | 属性attr!=value的E | |
$(‘E[attr ^=value]') | 属性attr以value开头的E | |
$(‘E[attr $=value]') | 属性attr以value结尾的E | |
$(‘E[attr *=value]') | 属性attr包含value的E | |
$(‘E[attr][attr *=value]') | 可以连用 | |
子元素过滤器 | ||
$(‘E:nth-child(n)') | E的第n个子节点 | |
$(‘E:nth-child(3n+1)') | E的index符合3n+1表达式的子节点 | |
$(‘E:nth-child(even)') | E的index为偶数的子节点 | |
$(‘E:nth-child(odd)') | E的index为奇数的子节点 | |
$(‘E:first-clild') | 所有E的第一个子节点 | |
$(‘E:last-clild') | 所有E的最后一个子节点 | |
$(‘E:only-clild') | 只有唯一子节点的E的子节点 | |
表单元素选择器 | ||
$(‘E:type') | 特定类型的input | |
$(‘:checked') | 被选中的checkbox或radio | |
$(‘option: selected') | 被选中的option |
.find(selector) finds the child nodes of each element in the collection
Get the descendants (child nodes) of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.filter(selector) filters the elements in the current collection
Reduce the set of matched elements to those that match the selector or pass the function's test.
Basic method
.ready(handler) method executed after document loading is completed, different from window.onload
Specify a function to execute when the DOM is fully loaded.
.each(function(index,element)) traverses each element in the collection
Iterate over a jQuery object, executing a function for each matched element.
jQuery.extend( target [, object1 ] [, objectN ] ) merge objects
Merge the contents of two or more objects together into the first object.
Get element
.eq(index) Gets a specific jQuery object in the jQuery object collection by index
Reduce the set of matched elements to the one at the specified index.
.eq(-index) Gets a specific jQuery object in the jQuery object collection in reverse order index
An integer indicating the position of the element, counting backwards from the last element in the set.
.get(index) Gets the DOM object of a specific index in the jQuery collection object (automatically converts the jQuery object into a DOM object)
Retrieve one of the DOM elements matched by the jQuery object.
.get() converts jQuery collection object to DOM collection object and returns
Retrieve the DOM elements matched by the jQuery object.
Search for a given element from among the matched elements.
1. Return the first element index without parameters
2. If the parameter is a DOM object or jQuery object, the index of the parameter in the collection is returned
3. If the parameter is a selector, return the index of the first matching element. If not found, return -1
.clone([withDataAndEvents][,deepWithDataAndEvents]) creates a deep copy of the jQuery collection (sub-elements will also be copied). By default, the shuju and binding events of the object are not copied
Create a deep copy of the set of matched elements.
.parent([selector]) Gets the parent element of the jQuery object that matches the selector
Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
.parents([selector]) Gets the ancestor elements of the jQuery object that match the selector
Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
Insert element
.append(content[,content]) / .append(function(index,html)) Append content to the end of the object
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
1. You can add multiple contents at one time, and the content can be DOM objects, HTML strings, and jQuery objects
2. If the parameter is a function, the function can return a DOM object, HTML string, or jQuery object. The parameter is the position of the element in the collection and the original html value
.appendTo(target) inserts the object at the end of the target element. The target element can be a selector, DOM object, HTML string, element collection, jQuery object;
Insert every element in the set of matched elements to the end of the target.
Test
" ).appendTo( ".inner" );.prepend(content[,content]) / .prepend(function(index,html)) Append content to the head of the object. The usage is similar to append
Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
Test
" );.prependTo(target) inserts the object into the head of the target element. The usage is similar to prepend
Insert every element in the set of matched elements to the beginning of the target.
Test
" ). prependTo( ".inner" );.before([content][,content]) / .before(function) Insert content in front of the object (not at the head, but outside, and at the same level as the object). The parameters are similar to append
Insert content, specified by the parameter, before each element in the set of matched elements.
.insertBefore(target) inserts the object before the target (also not the head, but the same level)
Insert every element in the set of matched elements before the target.
.after([content][,content]) / .after(function(index)) Contrary to before, insert content, parameters and append after the object (not at the tail, but outside, at the same level as the object) Similar to
Insert content, specified by the parameter, after each element in the set of matched elements.
.insertAfter(target) is the opposite of insertBefore, inserting the object after the target (also not at the tail, but at the same level)
Insert every element in the set of matched elements after the target.
Test
" ).insertAfter( ".inner" );Wrapping element
.wrap(wrappingElement) / .wrap(function(index)) wraps an HTML structure for each object, which can be selector, element, HTML string, jQuery object
Wrap an HTML structure around each element in the set of matched elements.
.wrapAll(wrappingElement) wraps all matching objects in the same HTML structure
Wrap an HTML structure around all elements in the set of matched elements.
.wrapInner(wrappingElement) / .wrapInner(function(index)) wraps the matching element content. This is hard to explain. You will understand it just by looking at the example
Wrap an HTML structure around the content of each element in the set of matched elements.
.unwap() removes the parent of the DOM element
Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
Attribute methods
.val() gets the value of the element
Get the current value of the first element in the set of matched elements.
.val(value) /.val(function(index,value)) Set the value for the element. Index and value also refer to the index and original value of the element when setting it for each element in the collection
Set the value of each element in the set of matched elements.
.attr(attributeName) gets the value of a specific attribute of the element
Get the value of an attribute for the first element in the set of matched elements.
.attr(attributeName,value) / .attr(attributesJson) / .attr( attributeName, function(index, attr) ) Assign values to element attributes
Set one or more attributes for the set of matched elements.
$( "#greatphoto" ).attr({
alt: "Beijing Brush Seller",
title: "photo by Kelly Clark"
});
$( "#greatphoto" ).attr( "title", function( i, val ) {
return val " - photo by Kelly Clark";
});
.prop( propertyName ) Gets the value of a certain attribute of the element
Get the value of a property for the first element in the set of matched elements.
.prop(propertyName,value) / .prop(propertiesJson) / .prop(propertyName,function(index,oldPropertyValue)) Assign values to element properties
Set one or more properties for the set of matched elements.
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
return !val;
});
$( "input[type='checkbox']" ).prop({
disabled: true
});
For the difference between attribute and property, you can take a look at jQuery’s attr and prop
.data(key,value) / .value(json) adds data to HTML DOM elements. HTML5 elements already have data-* attributes
Store arbitrary data associated with the matched elements.The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
.data(key) / .data() Get the data set by data or the data in the HTML5 data-* attribute
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
alert( $( "body" ).data( "foo" ) ); // undefined
$( "body" ).data( "bar", "foobar" );
alert( $ ( "body" ).data( "bar" ) ); // foobar
CSS method
.hasClass(calssName) checks whether the element contains a certain class and returns true/false
Determine whether any of the matched elements are assigned the given class.
.addClass(className) / .addClass(function(index,currentClass)) Adds a class to an element. It does not overwrite the original class, but appends it, and does not check for duplicates
Adds the specified class(es) to each of the set of matched elements.
$( "ul li" ).addClass(function( index ) {
return "item-" index;
});
removeClass([className]) / ,removeClass(function(index,class)) removes single/multiple/all classes
Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
.toggleClass(className) /.toggleClass(className,switch) / .toggleClass([switch]) / .toggleClass( function(index, class, switch) [, switch ] ) toggle means switch, and the method is used Switch, switch is a bool type value, you can understand this by looking at the example
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
First execution
// Both ways of writing have the same meaning
if ( addOrRemove ) {
$( "#foo" ).addClass( className );
} else {
$( "#foo" ).removeClass( className );
}
.css(propertyName) / .css(propertyNames) Get the value of the specific property of the element style
Get the value of style properties for the first element in the set of matched elements.
var styleProps = $( this ).css([
"width", "height", "color", "background-color"
]);
.css(propertyName,value) / .css( propertyName, function(index, value) ) / .css( propertiesJson ) Set the value of a specific property of element style
Set one or more CSS properties for the set of matched elements.
$( this ).css( "width", " =200" );
$( this ).css( "background-color", "yellow" );
$( this ).css({
"background-color": "yellow",
"font-weight": "bolder"
});
Event method
.bind( eventType [, eventData ], handler(eventObject) ) Bind event handler, this is often used, not much explanation
Attach a handler to an event for the elements.
.delegate( selector, eventType, handler(eventObject) ) Let’s see the official explanation for this
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
.on( events [, selector ] [, data ], handler(eventObject) ) Recommended after 1.7, replacing bind, live, delegate
Attach an event handler function for one or more events to the selected elements.
For the differences between bind, live, delegate, and on, you can see jQuery’s three event binding methods.bind(), .live(), .delegate()
.trigger( eventType [, extraParameters ] ) JavaScript trigger element binding event
Execute all handlers and behaviors attached to the matched elements for the given event type.
.toggle( [duration ] [, complete ] ) / .toggle( options ) Hide or show elements
Display or hide the matched elements.
Animation/Ajax
These two parts have a lot of content and are not just a simple function. Here are just a list of common method names. For their use, you can see jQuery API animation ajax, or jQuery animation processing summary, ASP.NET uses Ajax animation
queue/dequeue/clearQueue
delay/stop
fadeIn/fadeOut/fadeTo/fadeToggle
slideUp/slideDown/slideToggle
show/hide
Ajax
$.ajax
$.load
$.get
Finally
After understanding the above content, you can experience the power of jQuery when using jQuery for web development. This article is not a jQuery learning guide, it is just an introduction to common methods. If you want to learn jQuery, the best teaching material is jQuery API. The examples and English explanations in this article all come from jQuery API. In addition, the content introduced in the article is far from all jQuery, but mastering these first can give you a more comprehensive understanding of jQuery, and then you will be able to learn other content with ease.