最後更新: 2021-10-07
目錄
jQuery 介紹
* Only 32kB minified and gzipped. (no gzip: 94K)
* Cross-Browser
* JavaScript library
功能:
- Effects
- 更新 HTML (DOM)
- AJAX
Home Page:
http://jquery.com/
Download
Production jQuery
# min 版會細 size
wget http://code.jquery.com/jquery-1.11.1.min.js
CDN
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Usage
* By default jQuery uses the $ sign as a shortcut for jQuery.
# The noConflict() method returns a reference to jQuery
// Use full jQuery function name to reference jQuery.
var jq = $.noConflict();
jq(document).ready(function(){
jq("button").click(function(){
jq("p").text("jQuery is still working!");
});
});
Debug
console.log("debug msg");
jQuery Syntax
Syntax
$(selector).action()
# $.fn namespace ("jQuery prototype")
Methods called on jQuery selections are in the $.fn namespace,
and automatically receive and return the selection as this.
# $ namespace
Methods in the $ namespace are generally utility-type methods, and do not work with selections;
they are not automatically passed any arguments, and their return value will vary.
ie.
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" /> <script> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> <p>Click me away!</p> <p>Click me too!</p> </body> </html>
.load() 與 .ready()
.load()
event on the window object
# the code doesn't run until entire page (images or iframes) are finished(loaded)
window.onload = function() {
alert( "welcome" );
};
.ready()
# jQuery detects this state
# wait for the X(document) to be fully loaded and ready before working with it
# page's Document Object Model (DOM) becomes safe to manipulate
# $( document ).ready() shorthand $()
$( document ).ready(function() { // Handler for .ready() called. });
相等
$(function() { // Handler for .ready() called. });
選擇 Element
$(this).hide() - hides the current element
$("p").hide() - hides all <p> elements
$(".test").hide() - hides all elements with class="test"
$("#test").hide() - hides the element with id="test"
$("p.intro") Selects all <p> elements with class="intro"
$(":button") Selects all <button> elements and <input> elements of type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements
$("[href]") Selects all elements with an href attribute ( $("[name=input1]") )
event.preventDefault();
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "As you can see, the link no longer took you to jquery.com" );
// prevent the default behavior
event.preventDefault();
});
});
寫 JS 的位置
inline
<script> $(document).ready(function(){ $("tr:odd").css("background-color","yellow"); }); </script>
Functions In a Separate File
<script src="my_jquery_functions.js"></script>
Utility Methods
# $.trim()
$.trim( " lots of extra whitespace " );
# $.each()
# $.each // Iterates over arrays and objects: $.each([ "foo", "bar", "baz" ], function( idx, val ) { console.log( "element " + idx + " is " + val ); }); $.each({ foo: "bar", baz: "bim" }, function( k, v ) { console.log( k + " : " + v ); }); <ul> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> <li><a href="#">Link 3</a></li> </ul> $( "li" ).each( function( index, element ){ console.log( $( this ).text() ); }); // Logs the following: // Link 1 // Link 2 // Link 3
# $.inArray()
# Returns a value's index in an array, or -1 if the value is not in the array: var myArray = [ 1, 2, 3, 5 ]; if ( $.inArray( 4, myArray ) !== -1 ) { console.log( "found it!" ); }
# $.extend()
# If you don't want to change any of the objects you pass to $.extend(), pass an empty object as the first argument: var firstObject = { foo: "bar", a: "b" }; var secondObject = { foo: "baz" }; var newObject = $.extend( {}, firstObject, secondObject );
# $.proxy()
var myFunction = function() { console.log( this ); }; var myObject = { foo: "bar" }; myFunction(); // window var myProxyFunction = $.proxy( myFunction, myObject ); myProxyFunction(); // myObject
Events
click()
HTML
<div id="target"> Click here </div> <div id="other"> Trigger the handler </div>
JS
# event handler can be bound to any <div> $( "#target" ).click(function() { alert( "Handler for .click() called." ); });
* Any HTML element can receive this event.
# trigger the event when a different element is clicked
$( "#other" ).click(function() { $( "#target" ).click(); });
dblclick()
mouseenter()
$("#p1").mouseenter(function(){ alert("You entered p1!"); });
mouseleave()
mousedown()
mouseup()
hover()
$("#p1").hover(function(){ alert("You entered p1!"); }, function(){ alert("Bye! You now leave p1!"); });
focus()
$("input").focus(function(){ $(this).css("background-color","#cccccc"); });
blur()
.on 與 .off
# .on
Multiple Event Responses $( "input" ).on( "click change", // Bind handlers for multiple events function() { console.log( "An input was clicked or changed!" ); } ); $( "p" ).on({ "click": function() { console.log( "clicked!" ); }, "mouseover": function() { console.log( "hovered!" ); } }); var foo = function() { console.log( "foo" ); }; var bar = function() { console.log( "bar" ); }; $( "p" ).on( "click", foo ).on( "click", bar );
# .off
Tearing Down Event Listeners
To remove an event listener, you use the .off()
$( "p" ).off( "click" ); $( "p" ).off( "click", bar );
# .toggle()
triggered by the "click" event and accepts two or more functions.
// The toggle helper function $( "p.expander" ).toggle( function() {$( this ).prev().addClass( "open" );}, function() {$( this ).prev().removeClass( "open" );} );
Callback Functions
# the next line of code can be run even though the effect is not finished.
解決:
$("button").click(function(){
$("p").hide("slow",function(){
alert("The paragraph is now hidden");
});
});
# When $.get() finishes getting the page myhtmlpage.html, it executes the myCallBack() function.
$.get( "myhtmlpage.html", myCallBack );
Callback with Arguments
// 不可以這樣寫 $.get( "myhtmlpage.html", myCallBack( param1, param2 ) ); // 要這樣才正確 $.get( "myhtmlpage.html", function() { myCallBack( param1, param2 ); });
Chaining
allows us to run multiple jQuery methods (on the same element) within a single statement.
<script> $(document).ready(function() { $("button").click(function(){ $("#p1").css("color","red").slideUp(2000).slideDown(2000); }); }); </script>
Manipulating Elements
.html() – Get or set the HTML contents.
.text() – Get or set the text contents; HTML will be stripped.
$(document).ready(function(){ $("#btn1").click(function(){ alert("Text: " + $("#test").text()); }); $("#btn2").click(function(){ alert("HTML: " + $("#test").html()); }); });
.width() – Get or set the width in pixels of the first element in the selection as an integer.
.height() – Get or set the height in pixels of the first element in the selection as an integer.
.position() – Get an object with position information for the first element in the selection,
relative to its first positioned ancestor. This is a getter only.
.val() – Get or set the value of form elements.
i.e. set select option
<select id="gate"> <option value='null'>- choose -</option> <option value='Gateway 1'>Gateway 1</option> <option value='Gateway 2'>Gateway 2</option> </select> $(function() { $("#gate").val('Gateway 2'); });
# placing
# you don't get a reference to the newly created element:
- .after() # 放在 <> ... </> 之後
- .before()
- .append() # 夾在 <> ... </> 中間
- .prepend()
i.e.
$("body").append("<p>New element</p>");
# create a new element, it is not immediately added to the page
.insertAfter() # method places the selected element(s) after the element provided as an argument.
.insertBefore()
.appendTo()
.prependTo()
i.e.
var myNewElement = $("<p>New element</p>"); myNewElement.appendTo( "body" );
Attributes
.attr() – Get or set the value of the provided attribute.
# getter
$( "a" ).attr( "href" );
# setter
$( "a" ).attr( "href", "allMyHrefsAreTheSameNow.html" );
overloads
i.e.
// getter
$( "h1" ).html();
// setter
$( "h1" ).html( "hello world" );
i.e.
<style>
a.test {
font-weight: bold;
}
</style>
$( "h1" ).html().addClass( "test" );
# Chaining
$( "#content" )
.find( "h3" )
.eq( 2 )
.html( "new text for the third h3!" );
# Removing Elements
.remove() when you want to permanently remove the selection from the page.
.detach() Like .remove(), it returns the selection, but it also maintains the data and events
.empty() If you want to leave the element on the page but remove its contents
i.e.
$("#div1").remove();
$("#div1").empty();
$("p").remove(".italic");
# Creating New Elements
$( "<li class=\"new\">new list item</li>" );
// Creating a new element with an attribute object.
$( "<a/>", {
html: "This is a <strong>new</strong> link",
"class": "new",
href: "foo.html"
});
# performance
# there's a huge performance cost for adding to the DOM repeatedly.
var myItems = [];
var myList = $( "#myList" );
for ( var i = 0; i < 100; i++ ) {
myItems.push( "<li>item " + i + "</li>" );
}
myList.append( myItems.join( "" ) );
Selecting Elements
// All except the first three divs.
"div:gt(2)"
// Contain Any Elements
if ( $( "div.foo" ).length ) {
...
}
// Filtering Selections
$( "div.foo" ).has( "p" ); // div.foo elements that contain <p> tags
$( "h1" ).not( ".bar" ); // h1 elements that don't have a class of bar
$( "ul li" ).eq( 5 ); // the sixth
# pseudo-selector targets any "*"
:button
$( "form :button" );
:checkbox
$( "form :checkbox" );
:radio
$( "form :radio" );
:checked
$( "form :checked" );
:disabled
$( "form :disabled" );
:enabled
:image
# <input> elements that have a type="image":
:password
# <input> elements with a type="password":
Traversing
parents, children, and siblings
<div class="grandparent">
<div class="parent">
<div class="child">
<span class="subchild"></span>
</div>
</div>
<div class="surrogateParent1"></div>
<div class="surrogateParent2"></div>
</div>
// returns [ div.child ]
$( "span.subchild" ).parent();
// returns [ div.child, div.parent, div.grandparent ]
$( "span.subchild" ).parents();
// returns [ div.child, div.parent ]
$( "span.subchild" ).parentsUntil( "div.grandparent" );
---
// returns [ div.surrogateParent1 ]
$( "div.parent" ).next();
// Selecting a prev sibling of the selectors:
// returns [] as No sibling exists before div.parent
$( "div.parent" ).prev();
// returns [ div.surrogateParent1 ]
$( "div.surrogateParent2" ).prevAll().first();
// returns [ div.parent ]
$( "div.surrogateParent2" ).prevAll().last();
---
// returns [ div.surrogateParent1, div.surrogateParent2 ]
$( "div.parent" ).siblings();
// returns [ div.parent, div.surrogateParent1, div.surrogateParent2 ]
$( "div.grandparent" ).children( "div" );
DOM
// Setting the inner HTML with jQuery.
var target = document.getElementById( "target" );
$( target ).html( "<td>Hello <b>World</b>!</td>" );
// Inserting a new element after another with jQuery.
var target = document.getElementById( "target" );
var newElement = document.createElement( "div" );
$( target ).after( newElement );
Using CSS
# CSS properties that normally include a hyphen
# The CSS property font-size is expressed as fontSize when used as a property name in JavaScript
i.e.
$( "h1" ).css( "fontSize" );
$( "h1" ).css( "fontSize" );
$("p").css("background-color");
i.e.
$( "h1" ).css( "fontSize", "100px" );
$("p").css("background-color","yellow");
// Setting multiple properties.
$( "h1" ).css({
fontSize: "100px",
color: "red"
});
i.e.
$("button").click(function(){
$("h1,h2,p").addClass("blue");
});
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
if ( h1.hasClass( "big" ) ) {
...
}
width() & height()
// Sets the width of all <h1> elements.
$( "h1" ).width( "50px" );
// Gets the width of the first <h1> element.
$( "h1" ).width();
// Sets the height of all <h1> elements.
$( "h1" ).height( "50px" );
// Gets the height of the first <h1> element.
$( "h1" ).height();
position()
// Returns an object containing position information for
// the first <h1> relative to its "offset (positioned) parent".
$( "h1" ).position();
AJAX
In general, Ajax requests are limited to the same protocol (http or https),
the same port, and the same domain as the page making the request.
This limitation does not apply to scripts that are loaded via jQuery's Ajax methods(JSONP).
full-featured method: $.ajax()
simple convenience methods: $.get(), $.getScript(), $.getJSON(), $.post(), and $().load().
$.ajax()
$.ajax({url,data,type,success,error,complete});
// Using the core $.ajax() method $.ajax({ // The URL for the request url: "post.php", // The data to send (will be converted to a query string) data: { id: 123 }, // Whether this is a POST or GET request type: "GET", // The type of data we expect back dataType : "json", // Code to run if the request succeeds; // the response is passed to the function success: function( json ) { $( "<h1>" ).text( json.title ).appendTo( "body" ); $( "<div class=\"content\">").html( json.html ).appendTo( "body" ); }, // Code to run if the request fails; the raw request and // status codes are passed to the function error: function( xhr, status, errorThrown ) { alert( "Sorry, there was a problem!" ); console.log( "Error: " + errorThrown ); console.log( "Status: " + status ); console.dir( xhr ); }, // Code to run regardless of success or failure complete: function( xhr, status ) { alert( "The request is complete!" ); } });
.load()
fetches HTML from a URL, and uses the returned HTML to populate the selected element(s).
$(selector).load(URL,data,callback);
i.e.
$("#div1").load("demo_test.txt");
i.e.
$("button").click(function(){ $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){ if(statusTxt=="success") alert("External content loaded successfully!"); if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText); }); });
responseTxt - contains the resulting content if the call succeed
statusTxt - contains the status of the call
xhr - contains the XMLHttpRequest object
.getJSON
$.getJSON( "/details.php", function( resp ) {
// Log each key in the response data
$.each( resp, function( key, value ) {
console.log( key + " : " + value );
});
});
.get()
$.get(URL [,data] [, success] [, dataType]);
- data: "" <- Default
- success: callback function(data,status){}
-
dataType: The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, text, html).
i.e.
$.get( "foo.php", function( r ) { response = r; });
$.post(URL,data,callback);
# URL: you wish to request
# data: send along with the request
# callback: executed if the request succeeds
ie. html post data (test=1) without refresh
原理: Bind an event handler to the "click" JavaScript event
HTML
<form id="form-apply" action="/apply">
<input type="hidden" name="test" value="1">
</form>
<button id="btn-apply" class="btn btn-default btn-lg">apply</button>
JS
$("#btn-apply").click(function(){
var form = $("#form-apply");
var url = form.attr( "action" );
var data = form.serialize();
var posting = $.post( url, data );
console.log(data);
posting
.fail(function(){
alert( "error" );
})
.done(function(){
alert( "done" );
});
});
.done() .fail() .always()
jQuery's Ajax methods return a superset of the XMLHTTPRequest object.
The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always()
serialize()
// Turning form data into a query string $( "#myForm" ).serialize(); // Creates a query string like this: // field_1=something&field2=somethingElse
serializeArray()
// Creating an array of objects containing form data $( "#myForm" ).serializeArray(); // Creates a structure like this: // [ // { // name : "field_1", // value : "something" // }, // { // name : "field_2", // value : "somethingElse" // } // ]
Validate:
// Using validation to check for the presence of an input
$( "#form" ).submit(function( event ) {
// If .required's value's length is zero
if ( $( ".required" ).val().length === 0 ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});
// Validate a phone number field
$( "#form" ).submit(function( event ) {
var inputtedPhoneNumber = $( "#phone" ).val();
// Match only numbers
var phoneNumberRegex = /^\d*$/;
// If the phone number doesn't match the regex
if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});
Ajax Events
// Setting up a loading indicator using Ajax Events $( "#loading_indicator" ) .ajaxStart(function() { $( this ).show(); }).ajaxStop(function() { $( this ).hide(); });
Data Methods
// Storing
$( "#myDiv" ).data( "keyName", { foo: "bar" } );
// retrieving
$( "#myDiv" ).data( "keyName" );
# establish a relationship between a list item and a <div>
$( "#myList li" ).each(function() {
var li = $( this );
var div = li.find( "div.content" );
li.data( "contentDiv", div );
});
// Later, we don't have to find the div again;
// we can just read it from the list item's data
var firstLi = $( "#myList li:first" );
firstLi.data( "contentDiv" ).html( "new content" );
.index()
<ul> // parent
<div></div> // 0
<li id="foo1">foo</li> // 1
<li id="bar1">bar</li>
<li id="baz1">baz</li>
<div></div>
</ul>
var foo = $( "#foo1" );
console.log( "Index: " + foo.index() ); // 1
# In the first example, .index() gives the zero-based index of #foo1 within its parent.
Since #foo1 is the second child of its parent, index() returns 1.
<ul>
<div class="test"></div>
<li id="foo1">foo</li> <1>
<li id="bar1" class="test">bar</li> <2>
<li id="baz1">baz</li>
<div class="test"></div>
</ul>
<div id="last"></div>
var div = $( "#last" );
console.log( "Index: " + div.index( "div" ) ); // 2
jQuery is selecting all of the <div> elements in the document,
then searching for the index that contains the first element in the jQuery object .index() is called on.
var foo = $( "li" );
var baz = $( "#baz1" );
console.log( "Index: " + foo.index( baz ) ); // 2
var tests = $( ".test" );
var bar = $( "#bar1" );
console.log( "Index: " + tests.index( bar ) ); // 1
hide | show
$("button").click(function(){
$("p").toggle();
});
$("button").click(function(){
$("p").hide(1000);
});
$("#show").click(function(){
$("p").show();
});
$( "a" ).click(function( event ) {
event.preventDefault();
$( this ).hide( "slow" );
});
fadeIn
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>
fadeOut()
fadeToggle()
$(selector).fadeTo(speed,opacity,callback);
# 0 是透明
slide
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style type="text/css">
#panel,#flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
#panel
{
padding:50px;
display:none;
}
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
$(selector).slideUp(speed,callback);
$(selector).slideToggle(speed,callback);
animate
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:'250px'});
});
});
</script>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
});
});
});
</script>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
# Using Relative Values
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left:'250px',
height:'+=150px',
width:'+=150px'
});
});
});
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
height:'toggle'
});
});
});
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div=$("div");
div.animate({height:'300px',opacity:'0.4'},"slow");
div.animate({width:'300px',opacity:'0.8'},"slow");
div.animate({height:'100px',opacity:'0.4'},"slow");
div.animate({width:'100px',opacity:'0.8'},"slow");
});
});
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div=$("div");
div.animate({left:'100px'},"slow");
div.animate({fontSize:'3em'},"slow");
});
});
</script>
術語
- DOM = Document Object Model
Useful Example
auto refresh
<script> function redirect(){ window.location.href = "admin_panel" } setTimeout(redirect, 2000); </script>
auto close
$('[data-toggle="popover"]').popover().click(function () { setTimeout(function () { $('[data-toggle="popover"]').popover('hide'); }, 2000); });
button link
$('.button').click(function() { window.location = "/" + this.id; });
Tools
$.now()
jQuery.now()
相當於
(new Date).getTime()
Learn