#### 第4章:
#### jQuery
jQuery 是一個 JavaScript 庫。jQuery 很容易學習。
#### 4.1 jQuery 安裝
* 從 jquery.com下載 jQuery 庫
~~~
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
~~~
* 從 CDN 中載入 jQuery, 如從 Google 中加載 jQuery
~~~
<head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
</head>
~~~
#### 4.2 jQuery 語法
基礎語法: **$(selector).action()**
* 美元符號定義 jQuery
* 選擇符(selector)"查詢"和"查找" HTML 元素
* jQuery 的 action() 執行對元素的操作
實例:
* $(this).hide() - 隱藏當前元素
* $("p").hide() - 隱藏所有 元素
* $("p.test").hide() - 隱藏所有 class="test" 的 元素
* $("#test").hide() - 隱藏 id="test" 的元素
~~~
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
? <script>
? ? ? $(document).ready(function(){
? ? ? ? ? $("p").hide();
? ? ? })
? </script>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</body>
</html>
~~~
:-: 
通過`$("p").hide()`使所有的標簽元素被隱藏了。
##### 文檔就緒事件
防止文檔在完全加載(就緒)之前運行 jQuery 代碼,即在 DOM 加載完成后才可以對 DOM 進行操作。
~~~
$(document).ready(function(){
? // 執行代碼
});
或者
$(function(){
? // 執行代碼
});
~~~
JavaScript 入口函數:
~~~
window.onload = function () {
? // 執行代碼
}
~~~
jQuery 入口函數與 JavaScript 入口函數的區別:
* jQuery 的入口函數是在 html 所有標簽(DOM)都加載之后,就會去執行。
* JavaScript 的 window.onload 事件是等到所有內容,包括外部圖片之類的文件加載完后,才會執行。
#### 4.3 jQuery 選擇器
#id 選擇器
~~~
$(document).ready(function(){
$("button").click(function(){
? $("#test").hide();
});
});
~~~
.class 選擇器
~~~
$(document).ready(function(){
$("button").click(function(){
? $(".test").hide();
});
});
~~~
| 語法 | 描述 |
| --- | --- |
| $("\*") | 選取所有元素 |
| $(this) | 選取當前 HTML 元素 |
| $("p.intro") | 選取 class 為 intro 的 元素 |
| $("p:first") | 選取第一個 元素 |
| $("ul li:first") | 選取第一個 元素的第一個 元素 |
| $("ul li:first-child") | 選取每個 元素的第一個 元素 |
| $("\[href\]") | 選取帶有 href 屬性的元素 |
| $("a\[target='\_blank'\]") | 選取所有 target 屬性值等于 "\_blank" 的 元素 |
| $("a\[target!='\_blank'\]") | 選取所有 target 屬性值不等于 "\_blank" 的 元素 |
| $(":button") | 選取所有 type="button" 的 元素 和 元素 |
| $("tr:even") | 選取偶數位置的 元素 |
| $("tr:odd") | 選取奇數位置的 元素 |
#### 4.4 jQuery 事件
| 鼠標事件 | 鍵盤事件 | 表單事件 | 文檔/窗口事件 |
| --- | --- | --- | --- |
| click | keypress | submit | load |
| dblclick | keydown | change | resize |
| mouseenter | keyup | focus | scroll |
| mouseleave | | blur | unload |
| hover | | | |
##### click()
click() 方法是當按鈕點擊事件被觸發時會調用一個函數。
~~~
$("p").click(function(){
? // 動作觸發后執行的代碼!!
});
~~~
##### dblclick()
當雙擊元素時,會發生 dblclick 事件。
~~~
$("p").dblclick(function(){
$(this).hide();
});
~~~
例子:
~~~
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
? <script>
? ? ? $(document).ready(function(){
? ? ? ? ? $("p").dblclick(function(){
? ? ? ? ? ? ? $(this).hide();
? ? ? ? ? });
? ? ? })
? </script>
</head>
<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</body>
</html>
~~~
:-: 
:-:
:-: 
我們為所有`<p>`標簽元素添加了雙擊事件。所以當我雙擊2時,2所在的`<p>`元素被隱藏了。如果雙擊1、3、4它們同樣也會被隱藏。
##### mouseenter()
當鼠標指針穿過元素時,會發生 mouseenter 事件。
~~~
$("#p1").mouseenter(function(){
? alert('您的鼠標移到了 id="p1" 的元素上!');
});
~~~
##### mouseleave()
當鼠標指針離開元素時,會發生 mouseleave 事件。
mouseleave() 方法觸發 mouseleave 事件,或規定當發生 mouseleave 事件時運行的函數:
~~~
$("#p1").mouseleave(function(){
? alert("再見,您的鼠標離開了該段落。");
});
~~~
##### mousedown()
當鼠標指針移動到元素上方,并按下鼠標按鍵時,會發生 mousedown 事件。
~~~
$("#p1").mousedown(function(){
? alert("鼠標在該段落上按下!");
});
~~~
##### mouseup()
當在元素上松開鼠標按鈕時,會發生 mouseup 事件。
~~~
$("#p1").mouseup(function(){
? alert("鼠標在段落上松開。");
});
~~~
##### hover()
hover()方法用于模擬光標懸停事件。
~~~
$("#p1").hover(
? function(){
? ? ? alert("你進入了 p1!");
? },
? function(){
? ? ? alert("拜拜! 現在你離開了 p1!");
? }
);
~~~
##### focus()
當元素獲得焦點時,發生 focus 事件。
~~~
$("input").focus(function(){
$(this).css("background-color","#cccccc");
});
~~~
##### blur()
當元素失去焦點時,發生 blur 事件。
~~~
$("input").blur(function(){
$(this).css("background-color","#ffffff");
});
~~~
#### 3.5 jQuery方法
##### 3.5.1 常用方法
##### hide() 和 show()
~~~
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
~~~
可選的 speed 參數規定隱藏/顯示的速度,可以取以下值:"slow"、"fast" 或毫秒。
可選的 callback 參數是隱藏或顯示完成后所執行的函數名稱。
~~~
$("button").click(function(){
$("p").hide(1000,function(){
? ? alert("hide 已完成");
});
});
~~~
toggle() 方法來切換 hide() 和 show() 方法。
~~~
$("button").click(function(){
$("p").toggle();
});
~~~
##### 淡入淡出
* fadeIn()
* fadeOut()
* fadeToggle()
* fadeTo()
fadeIn() 用于淡入已隱藏的元素。
~~~
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
~~~
fadeOut() 方法用于淡出可見元素。
~~~
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
~~~
fadeToggle() 方法可以在 fadeIn() 與 fadeOut() 方法之間進行切換。
~~~
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
~~~
fadeTo() 方法允許漸變為給定的不透明度(值介于 0 與 1 之間)。
~~~
$("button").click(function(){
$("#div1").fadeTo("slow",0.15);
$("#div2").fadeTo("slow",0.4);
$("#div3").fadeTo("slow",0.7);
});
~~~
##### 滑動方法
slideDown() 方法用于向下滑動元素。
~~~
$("#flip").click(function(){
$("#panel").slideDown();
});
~~~
slideUp() 方法用于向上滑動元素。
~~~
$("#flip").click(function(){
$("#panel").slideUp();
});
~~~
slideToggle() 方法可以在 slideDown() 與 slideUp() 方法之間進行切換。
~~~
$("#flip").click(function(){
$("#panel").slideToggle();
});
~~~
##### 動畫 - animate()
~~~
$("button").click(function(){
$("div").animate({left:'250px'});
});
~~~
操作多個屬性
~~~
$("button").click(function(){
$("div").animate({
? left:'250px',
? opacity:'0.5',
? height:'150px',
? width:'150px'
});
});
~~~
操作相對值
~~~
$("button").click(function(){
$("div").animate({
? left:'250px',
? height:'+=150px',
? width:'+=150px'
});
});
~~~
動畫屬性設置為預定義值"show"、"hide" 或 "toggle"
~~~
$("button").click(function(){
$("div").animate({
height:'toggle'
});
});
~~~
動畫效果隊列
~~~
$("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");
});
~~~
##### 停止動畫
stop用于停止
~~~
$("#stop").click(function(){
$("#panel").stop();
});
~~~
##### 動畫回調
~~~
$("button").click(function(){
$("p").hide("slow",function(){
alert("段落現在被隱藏了");
});
});
~~~
##### 3.5.1 jQuery 鏈式方法
允許我們在相同的元素上運行多條 jQuery 命令,一條接著另一條.
~~~
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
~~~
~~~
$("#p1").css("color","red")
.slideUp(2000)
.slideDown(2000);
~~~
#### 3.6 獲取/設置內容和屬性
##### 獲得內容-text()、html() 以及 val()
~~~
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
$("#btn1").click(function(){
alert("值為: " + $("#test").val());
});
~~~
##### 設置內容 - text()、html() 以及 val()
~~~
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("RUNOOB");
});
~~~
text()、html() 以及 val() 的回調函數
~~~
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return "舊文本: " + origText + " 新文本: Hello world! (index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i,origText){
return "舊 html: " + origText + " 新 html: Hello <b>world!</b> (index: " + i + ")";
});
});
~~~
##### 獲取/設置屬性 - attr()
~~~
$("button").click(function(){
alert($("#runoob").attr("href"));
});
~~~
attr() 方法也用于設置/改變屬性值。
~~~
$("button").click(function(){
$("#runoob").attr("href","http://www.runoob.com/jquery");
});
~~~
arrt()的回調函數
~~~
$("button").click(function(){
$("#runoob").attr("href", function(i,origValue){
return origValue + "/jquery";
});
});
~~~
##### 添加元素
append() 方法在被選元素的結尾插入內容(仍然在該元素的內部)
~~~
$("p").append("追加文本");
~~~
prepend() 方法在被選元素的開頭插入內容
~~~
$("p").prepend("在開頭追加文本");
~~~
append() 和 prepend() 方法添加若干新元素
~~~
function appendText(){
var txt1="<p>文本-1。</p>"; // 使用 HTML 標簽創建文本
var txt2=$("<p></p>").text("文本-2。"); // 使用 jQuery 創建文本
var txt3=document.createElement("p");
txt3.innerHTML="文本-3。"; // 使用 DOM 創建文本 text with DOM
$("body").append(txt1,txt2,txt3); // 追加新元素
}
~~~
##### after() 和 before() 方法
jQuery after() 方法在被選元素之后插入內容。
jQuery before() 方法在被選元素之前插入內容。
~~~
$("img").after("在后面添加文本");
$("img").before("在前面添加文本");
~~~
##### after() 和 before() 方法添加若干新元素
~~~
function afterText()
{
var txt1="<b>I </b>"; // 使用 HTML 創建元素
var txt2=$("<i></i>").text("love "); // 使用 jQuery 創建元素
var txt3=document.createElement("big"); // 使用 DOM 創建元素
txt3.innerHTML="jQuery!";
$("img").after(txt1,txt2,txt3); // 在圖片后添加文本
}
~~~
##### 刪除元素/內容
如需刪除元素和內容,一般可使用以下兩個 jQuery 方法:
* remove() - 刪除被選元素(及其子元素)
~~~
$("#div1").remove();
$("p").remove(".italic"); 刪除.italic類的p元素
~~~
* empty() - 從被選元素中刪除子元素
~~~
$("#div1").empty();
~~~
##### 獲取并設置 CSS 類
* addClass() - 向被選元素添加一個或多個類
* removeClass() - 從被選元素刪除一個或多個類
* toggleClass() - 對被選元素進行添加/刪除類的切換操作
* css() - 設置或返回樣式屬性
~~~
.important
{
font-weight:bold;
font-size:xx-large;
}
.blue
{
color:blue;
}
~~~
##### addClass() 方法
~~~
$("button").click(function(){
$("h1,h2,p").addClass("blue");
$("div").addClass("important");
});
//規定多個類
$("button").click(function(){
$("body div:first").addClass("important blue");
});
~~~
##### removeClass() 方法
~~~
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
~~~
##### toggleClass() 方法。該方法對被選元素進行添加/刪除類的切換操作
~~~
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
~~~
#### css() 方法
##### 返回 CSS 屬性
~~~
$("p").css("background-color");
~~~
##### 設置 CSS 屬性
~~~
$("p").css("background-color","yellow");
~~~
##### 設置多個 CSS 屬性
~~~
$("p").css({"background-color":"yellow","font-size":"200%"});
~~~
#### 尺寸
* width()(返回元素寬度,不包括邊框和內邊距)
* height() (返回元素高度,不包括邊框和內邊距)
* innerWidth() (返回元素寬度,包括內邊距)
* innerHeight() (返回元素高度,包括內邊距)
* outerWidth() (返回元素寬度,包括邊框和內邊距)
* outerHeight() (返回元素高度,包括邊框和內邊距)

#### 3.7 jquery遍歷

圖示解析:
* `<div>` 元素是 `<ul>` 的父元素,同時是其中所有內容的祖先。
* `<ul>` 元素是 `<li>` 元素的父元素,同時是 `<div>` 的子元素
* 左邊的 `<li>` 元素是 `<span>` 的父元素,`<ul>` 的子元素,同時是 `<div>` 的后代。
* `<span>` 元素是 `<li>`的子元素,同時是 `<ul>` 和 `<div>` 的后代。
* 兩個 `<li>`元素是同胞(擁有相同的父元素)。
* 右邊的 `<li>` 元素是`<b>` 的父元素,`<ul>` 的子元素,同時是 `<div>`的后代。
* `<b>` 元素是右邊的`<li>` 的子元素,同時是`<ul>`和 `<div>`的后代。
##### 向上遍歷 DOM 樹
parent() 方法返回被選元素的直接父元素。
~~~
$(document).ready(function(){
$("span").parent();
});
~~~
parents() 方法返回被選元素的所有祖先元素
~~~
$(document).ready(function(){
$("span").parents();
});
~~~
parentsUntil() 方法返回介于兩個給定元素之間的所有祖先元素
~~~
$(document).ready(function(){
$("span").parentsUntil("div");
});
//返回介于span和div之間的祖先元素
~~~
##### 向下遍歷 DOM 樹
children() 方法返回被選元素的所有直接子元素。
~~~
$(document).ready(function(){
$("div").children();
});
~~~
find() 方法返回被選元素的后代元素,一路向下直到最后一個后代。
~~~
$(document).ready(function(){
$("div").find("span");
});
~~~
##### 在 DOM 樹中水平遍歷
siblings() 方法返回被選元素的所有同胞元素。
~~~
$(document).ready(function(){
$("h2").siblings();
});
~~~
next() 方法返回被選元素的下一個同胞元素。
~~~
$(document).ready(function(){
$("h2").next();
});
~~~
nextAll() 方法返回被選元素的所有跟隨的同胞元素。
~~~
$(document).ready(function(){
$("h2").nextAll();
});
~~~
nextUntil() 方法返回介于兩個給定參數之間的所有跟隨的同胞元素。
~~~
$(document).ready(function(){
$("h2").nextUntil("h6");
});
~~~
##### 縮小搜索元素的范圍
first() 方法返回被選元素的首個元素。
~~~
$(document).ready(function(){
$("div p").first();
});
~~~
last() 方法返回被選元素的最后一個元素。
~~~
$(document).ready(function(){
$("div p").last();
});
~~~
eq() 方法返回被選元素中帶有指定索引號的元素。
~~~
$(document).ready(function(){
$("p").eq(1); //選取第二個p元素,下標從0開始
});
~~~
filter() 方法允許您規定一個標準。不匹配這個標準的元素會被從集合中刪除,匹配的元素會被返回。
~~~
$(document).ready(function(){
$("p").filter(".url");
});
~~~
not() 方法返回不匹配標準的所有元素。
提示:not() 方法與 filter() 相反。
~~~
$(document).ready(function(){
$("p").not(".url");
});
~~~
#### 3.8 Jquery-AJAX
load() 方法從服務器加載數據,并把返回的數據放入被選元素中。
~~~
$("#div1").load("demo_test.txt");
$("#div1").load("demo_test.txt #p1");// 把demo_test.txt 中p1指定到div中去
~~~
這是示例文件("demo\_test.txt")的內容:
~~~
<h2>jQuery AJAX 是個非常棒的功能!</h2>
<p id="p1">這是段落的一些文本。</p>
~~~
可選的 callback 參數規定當 load() 方法完成后所要允許的回調函數。回調函數可以設置不同的參數:
* *responseTxt* - 包含調用成功時的結果內容
* *statusTXT* - 包含調用的狀態
* *xhr* - 包含 XMLHttpRequest 對象
~~~
$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("外部內容加載成功!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
~~~
##### AJAX get() 和 post() 方法
$.get() 方法通過 HTTP GET 請求從服務器上請求數據。
~~~
$("button").click(function(){
$.get("demo_test.php",function(data,status){
alert("數據: " + data + "\n狀態: " + status);
});
});
~~~
$.post() 方法通過 HTTP POST 請求向服務器提交數據。
~~~
$("button").click(function(){
$.post("/try/ajax/demo_test_post.php",
{
name:"spring",
url:"http://www.xxx.com"
},
function(data,status){
alert("數據: \n" + data + "\n狀態: " + status);
});
});
~~~
* *data* - 包含來自請求的結果數據
* *status* - 包含請求的狀態("success"、"notmodified"、"error"、"timeout"、"parsererror")
* *xhr* - 包含 XMLHttpRequest 對象
| 方法 | 描述 |
| --- | --- |
| $.ajax() | 執行異步 AJAX 請求 |
| $.ajaxPrefilter() | 在每個請求發送之前且被 $.ajax() 處理之前,處理自定義 Ajax 選項或修改已存在選項 |
| $.ajaxSetup() | 為將來的 AJAX 請求設置默認值 |
| $.ajaxTransport() | 創建處理 Ajax 數據實際傳送的對象 |
| $.get() | 使用 AJAX 的 HTTP GET 請求從服務器加載數據 |
| $.getJSON() | 使用 HTTP GET 請求從服務器加載 JSON 編碼的數據 |
| $.getScript() | 使用 AJAX 的 HTTP GET 請求從服務器加載并執行 JavaScript |
| $.param() | 創建數組或對象的序列化表示形式(可用于 AJAX 請求的 URL 查詢字符串) |
| $.post() | 使用 AJAX 的 HTTP POST 請求從服務器加載數據 |
| ajaxComplete() | 規定 AJAX 請求完成時運行的函數 |
| ajaxError() | 規定 AJAX 請求失敗時運行的函數 |
| ajaxSend() | 規定 AJAX 請求發送之前運行的函數 |
| ajaxStart() | 規定第一個 AJAX 請求開始時運行的函數 |
| ajaxStop() | 規定所有的 AJAX 請求完成時運行的函數 |
| ajaxSuccess() | 規定 AJAX 請求成功完成時運行的函數 |
| load() | 從服務器加載數據,并把返回的數據放置到指定的元素中 |
| serialize() | 編碼表單元素集為字符串以便提交 |
| serializeArray() | 編碼表單元素集為 names 和 values 的數組 |
標準ajax寫法:
~~~
$.ajax({
url:url, //地址
type:'post', //請求方式 還可以是get
dataType:'html', //返回格式 ,還可以是json
async:false, //同步異步 ,一般為異步flase
data:{"id":"value"}, //參數值
beforesend:function(){ // 請求前的處理
},
success:function(){ //請求成功時的處理
},
complete:function(){ //請求完成時的處理
},
error:function(){ //請求出錯誤時的處理
}
});
~~~