search
HomeWeb Front-endJS TutorialOnly 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的选择器就很简单了,不再详细一一说明

$(‘E~F’) Ordinary adjacent selector (younger brother selector), matches the $(‘.class1.class2’)Match elements whose class name contains both class1 and class2$("E:first")The first of all E$("E:last")The last of all E$("E:not(selector)")Filter E by selector$("E:even")      The index in all E is an even number$("E:odd")                                            $("E:eq(n)")                                                   All elements with index n in E$("E:gt(n)")                                                   All elements in E with index greater than nAll elements in E with index less than n$(":header")Select h1~h7 elements$("div:animated")Select the element that is performing the animation effect$(‘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 containing a tag $(‘E: parent')The parent element is the element of E, $('td: parent'): The parent element is the element of td$(‘E:hidden’)All hidden E$(‘E:visible’)All visible E
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
sibling element F of after E element (whether directly adjacent or not)
Basic Filter Selector
The index in all E is an odd number
$("E:ll(n)")                                                    
Content Filter
Visual Selector
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

Filtering method

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

Copy code The code is as follows:
$('li.item-ii').find('li ').css('background-color', 'red');

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

Copy code The code is as follows:
$('li').filter(':even'). css('background-color', 'red');

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.

Copy code The code is as follows:

$(document).ready(function() {
// Handler for .ready() called.
});

.each(function(index,element)) traverses each element in the collection

Iterate over a jQuery object, executing a function for each matched element.

Copy code The code is as follows:

$("li" ).each(function( index ) {
console.log( index ": " $(this).text() );
});

jQuery.extend( target [, object1 ] [, objectN ] ) merge objects

Merge the contents of two or more objects together into the first object.

Copy code The code is as follows:
var object = $.extend({}, object1, object2);

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.

Copy code The code is as follows:
$( "li" ).eq( 2 ).css( " background-color", "red" );

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

Copy code The code is as follows:
console.log( $( "li" ).get( -1 ) );

.get() converts jQuery collection object to DOM collection object and returns

Retrieve the DOM elements matched by the jQuery object.

Copy code The code is as follows:
console.log( $( "li" ).get() ) ;


.index() / .index(selector)/ .index(element) Find a specific element index from the given collection

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

Copy code The code is as follows:

var listItem = $( "#bar" );
alert( "Index: " $( "li" ).index( listItem ) );

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

Copy code The code is as follows:
$( ".hello" ).clone().appendTo( " .goodbye" );

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

Copy code The code is as follows:
$( "li.item-a" ).parent('ul ').css( "background-color", "red" );

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

Copy code The code is as follows:
$( "span.selected" ) .parents( "div" ) .css( "border", "2px red solid" )

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

Copy code The code is as follows:

$( ".inner" ).append( "< ;p>Test" );
$( "body" ).append( $newdiv1, [ newdiv2, existingdiv1 ] );
$( "p" ).append( " Hello" );
$( "p" ).append( $( "strong" ) );
$( "p" ).append( document.createTextNode( "Hello" ) );

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

Copy code The code is as follows:

$( "h2" ).appendTo( $( " .container" ) );
$( "

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.

Copy code The code is as follows:
$( ".inner" ).prepend( "

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.

Copy code The code is as follows:
$( "

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.

Copy code The code is as follows:

$( ".inner" ).before( "< ;p>Test" );
$( ".container" ).before( $( "h2" ) );
$( "p" ).first().before( newdiv1, [ newdiv2, existingdiv1 ] );
$( "p" ).before( "Hello" );
$( "p" ).before( document.createTextNode( "Hello " ) );

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

Copy code The code is as follows:
$( "h2" ).insertBefore( $( ".container" ) );

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

Copy code The code is as follows:

$( ".inner" ).after( "< ;p>Test" );
$( "p" ).after( document.createTextNode( "Hello" ) );

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

Copy code The code is as follows:

$( "

Test

" ).insertAfter( ".inner" );
$( "p" ).insertAfter( "#foo" );

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.

Copy code The code is as follows:


Hello

Goodbye

$( ".inner" ). wrap( "
" );


Hello



Goodbye< ;/div>


.wrapAll(wrappingElement) wraps all matching objects in the same HTML structure

Wrap an HTML structure around all elements in the set of matched elements.

Copy code The code is as follows:


Hello

Goodbye

$( ".inner" ). wrapAll( "
");


Hello

Goodbye



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

Copy code The code is as follows:


Hello

Goodbye

$( ".inner" ). wrapInner( "
");


Hello



Goodbye< ;/div>


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

Copy code The code is as follows:
pTags = $( "p" ).unwrap();

Attribute methods

.val() gets the value of the element

Get the current value of the first element in the set of matched elements.

Copy code The code is as follows:

$( "input:checkbox:checked" ).val ();

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

Copy code The code is as follows:

$( "input" ).val( 'hello' );
$( "input" ).on( "blur", function() {
$( this ).val(function( i, val ) {
return val.toUpperCase();
});
});

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

Copy code The code is as follows:

var title = $( "em" ).attr( "title" );

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

Copy code The code is as follows:

$( "#greatphoto" ).attr( "alt ", "Beijing Brush Seller" );

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

Copy code The code is as follows:

$( elem ).prop( "checked" )

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

Copy code The code is as follows:

$( "input" ).prop( "checked" , true );

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

Copy code The code is as follows:

$( "body" ).data( "foo" , 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1 , 2, 3 ] } );

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

Copy code The code is as follows:

alert( $( "body" ).data( "foo" ) );
alert( $( "body" ).data() );

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.

Copy code The code is as follows:
$( "#mydiv" ).hasClass( "foo" )

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

Copy code The code is as follows:

$( "p" ).addClass( "myClass yourClass " );

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

Copy code The code is as follows:

$( "p" ).removeClass( "myClass yourClass " );
$( "li:last" ).removeClass(function() {
return $( this ).prev().attr( "class" );
});

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

Some text.

First execution

Copy code The code is as follows:

$( "div. tumble" ).toggleClass( "bounce" )
Some text.


Second execution

Copy code The code is as follows:

$( "div.tumble" ).toggleClass( " bounce" )
Some text.

Copy code The code is as follows:

$( "#foo" ).toggleClass( className, addOrRemove );

// Both ways of writing have the same meaning

if ( addOrRemove ) {
$( "#foo" ).addClass( className );
} else {
$( "#foo" ).removeClass( className );
}

Copy code The code is as follows:

$( "div.foo" ).toggleClass(function () {
if ( $( this ).parent().is( ".bar" ) ) {
return "happy";
} else {
return "sad";
}
});

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

Copy code The code is as follows:

var color = $( this ).css( "background -color" );

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.

Copy code The code is as follows:

$( "div.example" ).css( " width", function( index ) {
return index * 50;
});

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

Copy code The code is as follows:

$( "#foo" ).bind( "click ", function() {
alert( "User clicked on 'foo.'" );
});

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

Copy code The code is as follows:

$( "table" ).on( "click" , "td", function() {//Tie the click event handler of td to the table like this
$( this ).toggleClass( "chosen" );
});

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

Copy code The code is as follows:

$( "#dataTable tbody" ).on( " click", "tr", function() {
alert( $( this ).text() );
});

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.

Copy code The code is as follows:

$( "#foo" ).trigger( "click " );

.toggle( [duration ] [, complete ] ) / .toggle( options ) Hide or show elements

Display or hide the matched elements.

Copy code The code is as follows:

$( ".target" ).toggle(); $( "#clickme" ).click(function() {
$( "#book" ).toggle( "slow", function() {
// Animation complete.
});
});

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.

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
jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

jquery中apply()方法怎么用jquery中apply()方法怎么用Apr 24, 2022 pm 05:35 PM

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

jquery on()有几个参数jquery on()有几个参数Apr 21, 2022 am 11:29 AM

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft