最新消息:博主的视频课程:Django高级实战教程 开发企业级问答网站开发

jQuery入门学习手册

编程技术 liaogx 来源:西部世界 1133浏览 0评论

/* 文中所有链接“科学上网”才能访问。天朝“局域网”用户推荐jQuery API 中文在线手册 */

一、jQuery Tutorial

jQuery is a JavaScript Library. jQuery greatly simplifies JavaScript programming. jQuery is easy to learn.

Before you start studying jQuery, you should have a basic knowledge of:

  • HTML
  • CSS
  • JavaScript

The jQuery library contains the following features:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

There are several ways to start using jQuery on your web site. You can:

A. Google CDN:

<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”></script>
</head>

B. Microsoft CDN:

<head>
<script src=”https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js”></script>
</head>

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to “query (or find)” HTML elements
  • A jQuery action() to be performed on the element(s)

The Document Ready Event is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

$(document).ready(function(){

   // jQuery methods go here…

});

二、jQuery Selectors

Use our jQuery Selector Tester to demonstrate the different selectors.

Selector

Example

Selects

*

$(“*”)

All elements

#id

$(“#lastname”)

The element with id=”lastname”

.class

$(“.intro”)

All elements with class=”intro”

.class,.class

$(“.intro,.demo”)

All elements with the class “intro” or “demo”

element

$(“p”)

All <p> elements

el1,el2,el3

$(“h1,div,p”)

All <h1>, <div> and <p> elements

:first

$(“p:first”)

The first <p> element

:last

$(“p:last”)

The last <p> element

:even

$(“tr:even”)

All even <tr> elements

:odd

$(“tr:odd”)

All odd <tr> elements

:first-child

$(“p:first-child”)

All <p> elements that are the first child of their parent

:first-of-type

$(“p:first-of-type”)

All <p> elements that are the first <p> element of their parent

:last-child

$(“p:last-child”)

All <p> elements that are the last child of their parent

:last-of-type

$(“p:last-of-type”)

All <p> elements that are the last <p> element of their parent

:nth-child(n)

$(“p:nth-child(2)”)

All <p> elements that are the 2nd child of their parent

:nth-last-child(n)

$(“p:nth-last-child(2)”)

All <p> elements that are the 2nd child of their parent, counting from the last child

:nth-of-type(n)

$(“p:nth-of-type(2)”)

All <p> elements that are the 2nd <p> element of their parent

:nth-last-of-type(n)

$(“p:nth-last-of-type(2)”)

All <p> elements that are the 2nd <p> element of their parent, counting from the last child

:only-child

$(“p:only-child”)

All <p> elements that are the only child of their parent

:only-of-type

$(“p:only-of-type”)

All <p> elements that are the only child, of its type, of their parent

parent > child

$(“div > p”)

All <p> elements that are a direct child of a <div> element

parent descendant

$(“div p”)

All <p> elements that are descendants of a <div> element

element + next

$(“div + p”)

The <p> element that are next to each <div> elements

element ~ siblings

$(“div ~ p”)

All <p> elements that are siblings of a <div> element

:eq(index)

$(“ul li:eq(3)”)

The fourth element in a list (index starts at 0)

:gt(no)

$(“ul li:gt(3)”)

List elements with an index greater than 3

:lt(no)

$(“ul li:lt(3)”)

List elements with an index less than 3

:not(selector)

$(“input:not(:empty)”)

All input elements that are not empty

:header

$(“:header”)

All header elements <h1>, <h2> …

:animated

$(“:animated”)

All animated elements

:focus

$(“:focus”)

The element that currently has focus

:contains(text)

$(“:contains(‘Hello’)”)

All elements which contains the text “Hello”

:has(selector)

$(“div:has(p)”)

All <div> elements that have a <p> element

:empty

$(“:empty”)

All elements that are empty

:parent

$(“:parent”)

All elements that are a parent of another element

:hidden

$(“p:hidden”)

All hidden <p> elements

:visible

$(“table:visible”)

All visible tables

:root

$(“:root”)

The document’s root element

:lang(language)

$(“p:lang(de)”)

All <p> elements with a lang attribute value starting with “de”

[attribute]

$(“[href]”)

All elements with a href attribute

[attribute=value]

$(“[href=’default.htm’]”)

All elements with a href attribute value equal to “default.htm”

[attribute!=value]

$(“[href!=’default.htm’]”)

All elements with a href attribute value not equal to “default.htm”

[attribute$=value]

$(“[href$=’.jpg’]”)

All elements with a href attribute value ending with “.jpg”

[attribute|=value]

$(“[title|=’Tomorrow’]”)

All elements with a title attribute value equal to ‘Tomorrow’, or starting with ‘Tomorrow’ followed by a hyphen

[attribute^=value]

$(“[title^=’Tom’]”)

All elements with a title attribute value starting with “Tom”

[attribute~=value]

$(“[title~=’hello’]”)

All elements with a title attribute value containing the specific word “hello”

[attribute*=value]

$(“[title*=’hello’]”)

All elements with a title attribute value containing the word “hello”

:input

$(“:input”)

All input elements

:text

$(“:text”)

All input elements with type=”text”

:password

$(“:password”)

All input elements with type=”password”

:radio

$(“:radio”)

All input elements with type=”radio”

:checkbox

$(“:checkbox”)

All input elements with type=”checkbox”

:submit

$(“:submit”)

All input elements with type=”submit”

:reset

$(“:reset”)

All input elements with type=”reset”

:button

$(“:button”)

All input elements with type=”button”

:image

$(“:image”)

All input elements with type=”image”

:file

$(“:file”)

All input elements with type=”file”

:enabled

$(“:enabled”)

All enabled input elements

:disabled

$(“:disabled”)

All disabled input elements

:selected

$(“:selected”)

All selected input elements

:checked

$(“:checked”)

All checked input elements

三、jQuery Events Methods

Event methods trigger or attach a function to an event handler for the selected elements.The following table lists all the jQuery methods used to handle events.

Method / Property

Description

bind()

Deprecated in version 3.0. Use the on() method instead. Attaches event handlers to elements

blur()

Attaches/Triggers the blur event

change()

Attaches/Triggers the change event

click()

Attaches/Triggers the click event

dblclick()

Attaches/Triggers the double click event

delegate()

Deprecated in version 3.0. Use the on() method instead. Attaches a handler to current, or future, specified child elements of the matching elements

die()

Removed in version 1.9. Removes all event handlers added with the live() method

error()

Removed in version 3.0. Attaches/Triggers the error event

event.currentTarget

The current DOM element within the event bubbling phase

event.data

Contains the optional data passed to an event method when the current executing handler is bound

event.delegateTarget

Returns the element where the currently-called jQuery event handler was attached

event.isDefaultPrevented()

Returns whether event.preventDefault() was called for the event object

event.isImmediatePropagationStopped()

Returns whether event.stopImmediatePropagation() was called for the event object

event.isPropagationStopped()

Returns whether event.stopPropagation() was called for the event object

event.namespace

Returns the namespace specified when the event was triggered

event.pageX

Returns the mouse position relative to the left edge of the document

event.pageY

Returns the mouse position relative to the top edge of the document

event.preventDefault()

Prevents the default action of the event

event.relatedTarget

Returns which element being entered or exited on mouse movement.

event.result

Contains the last/previous value returned by an event handler triggered by the specified event

event.stopImmediatePropagation()

Prevents other event handlers from being called

event.stopPropagation()

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event

event.target

Returns which DOM element triggered the event

event.timeStamp

Returns the number of milliseconds since January 1, 1970, when the event is triggered

event.type

Returns which event type was triggered

event.which

Returns which keyboard key or mouse button was pressed for the event

focus()

Attaches/Triggers the focus event

focusin()

Attaches an event handler to the focusin event

focusout()

Attaches an event handler to the focusout event

hover()

Attaches two event handlers to the hover event

keydown()

Attaches/Triggers the keydown event

keypress()

Attaches/Triggers the keypress event

keyup()

Attaches/Triggers the keyup event

live()

Removed in version 1.9. Adds one or more event handlers to current, or future, selected elements

load()

Removed in version 3.0. Attaches an event handler to the load event

mousedown()

Attaches/Triggers the mousedown event

mouseenter()

Attaches/Triggers the mouseenter event

mouseleave()

Attaches/Triggers the mouseleave event

mousemove()

Attaches/Triggers the mousemove event

mouseout()

Attaches/Triggers the mouseout event

mouseover()

Attaches/Triggers the mouseover event

mouseup()

Attaches/Triggers the mouseup event

off()

Removes event handlers attached with the on() method

on()

Attaches event handlers to elements

one()

Adds one or more event handlers to selected elements. This handler can only be triggered once per element

$.proxy()

Takes an existing function and returns a new one with a particular context

ready()

Specifies a function to execute when the DOM is fully loaded

resize()

Attaches/Triggers the resize event

scroll()

Attaches/Triggers the scroll event

select()

Attaches/Triggers the select event

submit()

Attaches/Triggers the submit event

toggle()

Removed in version 1.9. Attaches two or more functions to toggle between for the click event

trigger()

Triggers all events bound to the selected elements

triggerHandler()

Triggers all functions bound to a specified event for the selected elements

unbind()

Deprecated in version 3.0. Use the off() method instead. Removes an added event handler from selected elements

undelegate()

Deprecated in version 3.0. Use the off() method instead. Removes an event handler to selected elements, now or in the future

unload()

Removed in version 3.0. Attaches an event handler to the unload event

四、、jQuery Effects Methods

The following table lists all the jQuery methods for creating animation effects.

Method

Description

animate()

Runs a custom animation on the selected elements

clearQueue()

Removes all remaining queued functions from the selected elements

delay()

Sets a delay for all queued functions on the selected elements

dequeue()

Removes the next function from the queue, and then executes the function

fadeIn()

Fades in the selected elements

fadeOut()

Fades out the selected elements

fadeTo()

Fades in/out the selected elements to a given opacity

fadeToggle()

Toggles between the fadeIn() and fadeOut() methods

finish()

Stops, removes and completes all queued animations for the selected elements

hide()

Hides the selected elements

queue()

Shows the queued functions on the selected elements

show()

Shows the selected elements

slideDown()

Slides-down (shows) the selected elements

slideToggle()

Toggles between the slideUp() and slideDown() methods

slideUp()

Slides-up (hides) the selected elements

stop()

Stops the currently running animation for the selected elements

toggle()

Toggles between the hide() and show() methods

A. jQuery Callback Functions

JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.To prevent this, you can create a callback function.A callback function is executed after the current effect is finished.

Typical syntax: $(selector).hide(speed,callback);

Example with Callback

$(“button”).click(function(){
    $(“p”).hide(“slow”, function(){
        alert(“The paragraph is now hidden”);
    });
});

B. jQuery Method Chaining

Chaining allows us to run multiple jQuery commands, one after the other, on the same element(s).

Tip: This way, browsers do not have to find the same element(s) more than once.To chain an action, you simply append the action to the previous action.The following example chains together the css(), slideUp(), and slideDown() methods. The “p1” element first changes to red, then it slides up, and then it slides down:

Example 01

$(“#p1”).css(“color”, “red”).slideUp(2000).slideDown(2000);
Example 02
$(“#p1”).css(“color”, “red”)
  .slideUp(2000)
  .slideDown(2000);

五、jQuery HTML / CSS Methods

jQuery has several important methods for working with dimensions:

  • width()
  • height()
  • innerWidth()
  • innerHeight()
  • outerWidth()
  • outerHeight()

The following table lists all the methods used to manipulate the HTML and CSS.The methods below work for both HTML and XML documents. Exception: the html() method.

Method

Description

addClass()

Adds one or more class names to selected elements

after()

Inserts content after selected elements

append()

Inserts content at the end of selected elements

appendTo()

Inserts HTML elements at the end of selected elements

attr()

Sets or returns attributes/values of selected elements

before()

Inserts content before selected elements

clone()

Makes a copy of selected elements

css()

Sets or returns one or more style properties for selected elements

detach()

Removes selected elements (keeps data and events)

empty()

Removes all child nodes and content from selected elements

hasClass()

Checks if any of the selected elements have a specified class name

height()

Sets or returns the height of selected elements

html()

Sets or returns the content of selected elements

innerHeight()

Returns the height of an element (includes padding, but not border)

innerWidth()

Returns the width of an element (includes padding, but not border)

insertAfter()

Inserts HTML elements after selected elements

insertBefore()

Inserts HTML elements before selected elements

offset()

Sets or returns the offset coordinates for selected elements (relative to the document)

offsetParent()

Returns the first positioned parent element

outerHeight()

Returns the height of an element (includes padding and border)

outerWidth()

Returns the width of an element (includes padding and border)

position()

Returns the position (relative to the parent element) of an element

prepend()

Inserts content at the beginning of selected elements

prependTo()

Inserts HTML elements at the beginning of selected elements

prop()

Sets or returns properties/values of selected elements

remove()

Removes the selected elements (including data and events)

removeAttr()

Removes one or more attributes from selected elements

removeClass()

Removes one or more classes from selected elements

removeProp()

Removes a property set by the prop() method

replaceAll()

Replaces selected elements with new HTML elements

replaceWith()

Replaces selected elements with new content

scrollLeft()

Sets or returns the horizontal scrollbar position of selected elements

scrollTop()

Sets or returns the vertical scrollbar position of selected elements

text()

Sets or returns the text content of selected elements

toggleClass()

Toggles between adding/removing one or more classes from selected elements

unwrap()

Removes the parent element of the selected elements

val()

Sets or returns the value attribute of the selected elements (for form elements)

width()

Sets or returns the width of selected elements

wrap()

Wraps HTML element(s) around each selected element

wrapAll()

Wraps HTML element(s) around all selected elements

wrapInner()

Wraps HTML element(s) around the content of each selected element

六、jQuery Traversing Methods

Method

Description

add()

Adds elements to the set of matched elements

addBack()

Adds the previous set of elements to the current set

andSelf()

Deprecated in version 1.8. An alias for addBack()

children()

Returns all direct children of the selected element

closest()

Returns the first ancestor of the selected element

contents()

Returns all direct children of the selected element (including text and comment nodes)

each()

Executes a function for each matched element

end()

Ends the most recent filtering operation in the current chain, and return the set of matched elements to its previous state

eq()

Returns an element with a specific index number of the selected elements

filter()

Reduce the set of matched elements to those that match the selector or pass the function’s test

find()

Returns descendant elements of the selected element

first()

Returns the first element of the selected elements

has()

Returns all elements that have one or more elements inside of them

is()

Checks the set of matched elements against a selector/element/jQuery object, and return true if at least one of these elements matches the given arguments

last()

Returns the last element of the selected elements

map()

Passes each element in the matched set through a function, producing a new jQuery object containing the return values

next()

Returns the next sibling element of the selected element

nextAll()

Returns all next sibling elements of the selected element

nextUntil()

Returns all next sibling elements between two given arguments

not()

Remove elements from the set of matched elements

offsetParent()

Returns the first positioned parent element

parent()

Returns the direct parent element of the selected element

parents()

Returns all ancestor elements of the selected element

parentsUntil()

Returns all ancestor elements between two given arguments

prev()

Returns the previous sibling element of the selected element

prevAll()

Returns all previous sibling elements of the selected element

prevUntil()

Returns all previous sibling elements between two given arguments

siblings()

Returns all sibling elements of the selected element

slice()

Reduces the set of matched elements to a subset specified by a range of indices

七、jQuery AJAX Methods

AJAX is the art of exchanging data with a server, and update parts of a web page – without reloading the whole page.The following table lists all the jQuery AJAX methods:

Method

Description

$.ajax()

Performs an async AJAX request

$.ajaxPrefilter()

Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()

$.ajaxSetup()

Sets the default values for future AJAX requests

$.ajaxTransport()

Creates an object that handles the actual transmission of Ajax data

$.get()

Loads data from a server using an AJAX HTTP GET request

$.getJSON()

Loads JSON-encoded data from a server using a HTTP GET request

$.parseJSON()

Deprecated in version 3.0, use JSON.parse() instead. Takes a well-formed JSON string and returns the resulting JavaScript value

$.getScript()

Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request

$.param()

Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)

$.post()

Loads data from a server using an AJAX HTTP POST request

ajaxComplete()

Specifies a function to run when the AJAX request completes

ajaxError()

Specifies a function to run when the AJAX request completes with an error

ajaxSend()

Specifies a function to run before the AJAX request is sent

ajaxStart()

Specifies a function to run when the first AJAX request begins

ajaxStop()

Specifies a function to run when all AJAX requests have completed

ajaxSuccess()

Specifies a function to run when an AJAX request completes successfully

load()

Loads data from a server and puts the returned data into the selected element

serialize()

Encodes a set of form elements as a string for submission

serializeArray()

Encodes a set of form elements as an array of names and values

八、Query Miscellaneous Methods

As you already know; jQuery uses the $ sign as a shortcut for jQuery.There are many other popular JavaScript frameworks like: Angular, Backbone, Ember, Knockout, and more.What if other JavaScript frameworks also use the $ sign as a shortcut?If two different frameworks are using the same shortcut, one of them might stop working.The jQuery team have already thought about this, and implemented the noConflict() method.

You can of course still use jQuery, simply by writing the full name instead of the shortcut:

Example 01

$.noConflict();
jQuery(document).ready(function(){
    jQuery(“button”).click(function(){
        jQuery(“p”).text(“jQuery is still working!”);
    });
});

You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use. Here is an example:

Example 02

var jq = $.noConflict();
jq(document).ready(function(){
    jq(“button”).click(function(){
        jq(“p”).text(“jQuery is still working!”);
    });
});

If you have a block of jQuery code which uses the $ shortcut and you do not want to change it all, you can pass the $ sign in as a parameter to the ready method. This allows you to access jQuery using $, inside this function – outside of it, you will have to use “jQuery”:

Example 03

$.noConflict();
jQuery(document).ready(function($){
    $(“button”).click(function(){
        $(“p”).text(“jQuery is still working!”);
    });
});

Method

Description

data()

Attaches data to, or gets data from, selected elements

each()

Execute a function for each matched element

get()

Get the DOM elements matched by the selector

index()

Search for a given element from among the matched elements

$.noConflict()

Release jQuery’s control of the $ variable

$.param()

Create a serialized representation of an array or object (can be used as URL query string for AJAX requests)

removeData()

Removes a previously-stored piece of data

size()

Removed in version 3.0. Use the length property instead.

toArray()

Retrieve all the DOM elements contained in the jQuery set, as an array

转载请注明:西部世界 » jQuery入门学习手册

发表我的评论
取消评论

表情

网友最新评论 (1)

  1. 抄袭得真是太好了,都被我仔鸡感动了。! (∩_∩)
    匿名3年前 (2017-05-10)回复