jQuery 學習筆記(jQuery: The Return Flight)

第一課.

ajax:$.ajax(url[, settings])

?

練習代碼:

$(document).ready(function() {$("#tour").on("click", "button", function() {$.ajax('/photos.html', {success: function(response) {$('.photos').html(response).fadeIn();}});});
});
<div id="tour" data-location="london"><button>Get Photos</button><ul class="photos"></ul>
</div>

ajax 調用簡寫:$.get(url, success)

$(document).ready(function() {$("#tour").on("click", "button", function() {$.get('/photos.html', function(response) {$('.photos').html(response).fadeIn();});});
});

ajax?傳遞參數:直接在 url 中拼接或使用 data 對象傳遞,data: { "confNum": 1234 }

練習代碼:獲取網頁元素中的?data 屬性值作為 ajax 參數值傳遞

$(document).ready(function() {$("#tour").on("click", "button", function() {$.ajax('/photos.html', {success: function(response) {$('.photos').html(response).fadeIn();},data: { "location": $("#tour").data("location")}});});
});
<div id="tour" data-location="london"><button>Get Photos</button><ul class="photos"></ul>
</div>

第二課.

ajax?異常處理:error: function(request, errorType, errorMessage) { }

?

ajax?超時設定:timeout: 3000

?

ajax?調用前(beforeSend: function() {})完成后(complete: function() {})執行方法:

練習代碼:

$(document).ready(function() {var el = $("#tour");el.on("click", "button", function() {$.ajax('/photos.html', {data: {location: el.data('location')},success: function(response) {$('.photos').html(response).fadeIn();},error: function(request, errorType, errorMessage) {//var errmsg = $("<li>Error: " + errorType + " with message: " + errorMessage + "</li>");//$('.photos').append(errmsg);//alert('Error: ' + errorType + ' with message: ' + errorMessage);$('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');},timeout: 3000,beforeSend: function() {$("#tour").addClass("is-fetching")},complete: function() {$("#tour").removeClass("is-fetching")}});});
});
<div id="tour" data-location="london"><button>Get Photos</button><ul class="photos"></ul>
</div>

ajax 事件處理:處理 ajax 完成新增的標簽元素的事件

?

練習代碼:

$(document).ready(function() {function showPhotos() {$(this).find('span').slideToggle();}$('.photos').on('mouseenter', 'li', showPhotos).on('mouseleave', 'li', showPhotos);var el = $("#tour");el.on("click", "button", function() {$.ajax('/photos.html', {data: {location: el.data('location')},success: function(response) {$('.photos').html(response).fadeIn();},error: function() {$('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');},timeout: 3000,beforeSend: function() {$('#tour').addClass('is-fetching');},complete: function() {$('#tour').removeClass('is-fetching');}});});
});

HTML、AJAX Result

<div id="tour" data-location="london"><button>Get Photos</button><ul class="photos"></ul>
</div>
<li><img src="/assets/photos/paris1.jpg"><span style="display: none;">Arc de Triomphe</span>
</li>
<li><img src="/assets/photos/paris2.jpg"><span style="display: none;">The Eiffel Tower</span>
</li>
<li><img src="/assets/photos/london.jpg"><span style="display: none;">London</span>
</li>

第三課.?

JavaScript Objects:

練習代碼:

重構前:

$(document).ready(function() {$("#tour").on("click", "button", function() {$.ajax('/photos.html', {data: {location: $("#tour").data('location')},success: function(response) {$('.photos').html(response).fadeIn();},error: function() {$('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');},timeout: 3000,beforeSend: function() {$('#tour').addClass('is-fetching');},complete: function() {$('#tour').removeClass('is-fetching');}});});
});

重構為 JavaScript 對象 tour 后:

var tour = {init: function() {$("#tour").on("click", "button", this.fetchPhotos);},fetchPhotos: function() {$.ajax('/photos.html', {data: {location: $("#tour").data('location')},success: function(response) {$('.photos').html(response).fadeIn();},error: function() {$('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');},timeout: 3000,beforeSend: function() {$('#tour').addClass('is-fetching');},complete: function() {$('#tour').removeClass('is-fetching');}})}
}
$(document).ready(function() { tour.init();
});

第四課.

JavaScript Functions:重點理解 this 變量的作用域


ajax 回調函數中應用調用函數變量?this 時, 需要首先在 ajax 的 context 參數中傳入調用函數的 this 變量:

練習代碼:

function Tour(el) {var tour = this;this.el = el;this.photos = this.el.find('.photos');this.fetchPhotos = function() { $.ajax('/photos.html', {data: {location: tour.el.data('location')},context: tour,success: function(response) {this.photos.html(response).fadeIn();},error: function() {this.photos.html('<li>There was a problem fetching the latest photos. Please try again.</li>');},timeout: 3000,beforeSend: function() {this.el.addClass('is-fetching');},complete: function() {this.el.removeClass('is-fetching');}});}this.el.on('click', 'button', this.fetchPhotos);
}$(document).ready(function() { var paris = new Tour($('#paris'));var london = new Tour($('#london'));
});
<div id="paris" data-location="paris"><button>Get Paris Photos</button><ul class="photos"></ul>
</div><div id="london" data-location="london"><button>Get London Photos</button><ul class="photos"></ul>
</div>

第五課.

Ajax Forms

$('form').on('submit', function(event) {}); ?//表單提交事件

event.preventDefault(); //阻止瀏覽器的默認表單提交行為

type: 'POST' // POST 方式提交

data:{ "destination": $('#destination').val(),?"quantity": $('#quantity').val() } //獲取表單中的元素值提交數據

data: $('form').serialize() //通過表單序列化,提交整張表單中的數據

練習代碼:

$(document).ready(function() {$('form').on('submit', function(event) {event.preventDefault();$.ajax('/book', {type: 'POST',data: $('form').serialize(),success: function(response){$('.tour').html(response);}});});
});
<div class="tour" data-daily-price="357"><h2>Paris, France Tour</h2><p>$<span id="total">2,499</span> for <span id="nights-count">7</span> Nights</p><form action="/book" method="POST"><p><label for="nights">Number of Nights</label></p><p><input type="number" name="nights" id="nights" value="7"></p><input type="submit" value="book"></form>
</div>

第六課.

Ajax with JSON

dataType: 'json' // 通知服務器提交的數據類型為 json

contentType: 'application/json' //要求服務器返回的數據類型為 json

attr(<attribute>) //獲取 html 對象的屬性

attr(<attribute>, <value>) //給 html 對象的屬性賦值

?

?

練習代碼:

$(document).ready(function() {$('form').on('submit', function(event) {event.preventDefault();$.ajax($('form').attr('action'), {type: $('form').attr('method'),data: $('form').serialize(),dataType: 'json',success: function(response) {$('.tour').html('<p></p>').find('p').append('Trip to ' + response.description).append(' at $' + response.price).append(' for ' + response.nights + ' nights').append('. Confirmation: ' + response.confirmation);}});});
});
<div class="tour" data-daily-price="357"><h2>Paris, France Tour</h2><p>$<span id="total">2,499</span> for <span id="nights-count">7</span> Nights</p><form action="/book" method="POST"><p><label for="nights">Number of Nights</label></p><p><input type="number" name="nights" id="nights" value="7"></p><input type="submit" value="book"></form>
</div>

第七課.

Utility Methods

$.each(collection, function(<index>, <object>) {}) //iterate through the array

練習代碼:

$('button').on('click', function() {$.ajax('/cities/deals', {contentType: 'application/json',dataType: 'json',success: function(result) {$.each(result, function(index, dealItem) {var dealElement = $('.deal-' + index);dealElement.find('.name').html(dealItem.name);dealElement.find('.price').html(dealItem.price);});}});
});

$.getJSON(url, success); //result will be an array of?avaScript Objects

練習代碼:

$('button').on('click', function() {$.getJSON('/cities/deals', function(result) {$.each(result, function(index, dealItem) {var dealElement = $('.deal-' + index);dealElement.find('.name').html(dealItem.name);dealElement.find('.price').html(dealItem.price);});});
});

$.map(collection, function(<item>, <index>){});

練習代碼:

$('.update-available-flights').on('click', function() {$.getJSON('/flights/late', function(result) {var flightElements = $.map(result, function(flightItem, index){var liItem = $('<li></li>');liItem.append('<p>'+flightItem.flightNumber+'</p>');liItem.append('<p>'+flightItem.time+'</p>');return liItem;});$('.flight-times').html(flightElements);});
});

$.each vs $.map

?

.detach() //.detach() removes an element from the DOM, preserving all data and events.?

detach() 方法移除被選元素,包括所有文本和子節點。

這個方法會保留 jQuery 對象中的匹配的元素,因而可以在將來再使用這些匹配的元素。

detach() 會保留所有綁定的事件、附加的數據,這一點與 remove() 不同。

練習代碼:

$('.update-available-flights').on('click', function() {$.getJSON('/flights/late', function(result) {var flightElements = $.map(result, function(flightItem, index){var flightEl = $('<li>'+flightItem.flightNumber+'-'+flightItem.time+'</li>');return flightEl;});$('.flight-times').detach().html(flightElements).appendTo('.flights');});
});

第八課.

Managing Events:同一個元素同一個事件掛接多個事件處理程序,按順序執行

off(<event name>)?//停止事件的監聽,同時停止當前元素上指定事件的所有監聽,如:$('button').off('click');

Namespacing Events:給事件監聽程序命名,用于同一個元素,相同事件多個監聽程序時的區分和禁用、還原等操作

trigger(<event name>):觸發被選元素的指定事件類型

?

create a custom event:創建自定義事件后,可以通過代碼觸發的方式同時觸發多種頁面元素的監聽的相同的自定義事件。

$(<dom element>).on("<event>.<namespace>", <method>)

?

轉載于:https://www.cnblogs.com/cnshen/p/3944434.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273607.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273607.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273607.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Redis Hash 類型操作及常用命令

七個原則 Redis 是一個操作數據結構的語言工具&#xff0c;它提供基于 TCP 的協議以操作豐富的數據結構。在 Redis 中&#xff0c;數據結構這個詞的意義不僅表示在某種數據結構上的操作&#xff0c;更包括了結構本身及這些操作的時間空間復雜度。Redis 定位于一個內存數據庫&am…

Redis set 類型操作及常用命令

七個原則 Redis 是一個操作數據結構的語言工具&#xff0c;它提供基于 TCP 的協議以操作豐富的數據結構。在 Redis 中&#xff0c;數據結構這個詞的意義不僅表示在某種數據結構上的操作&#xff0c;更包括了結構本身及這些操作的時間空間復雜度。Redis 定位于一個內存數據庫&am…

緩存初解(五)---SpringMVC基于注解的緩存配置--web應用實例

之前為大家介紹了如何使用spring注解來進行緩存配置 &#xff08;EHCache 和 OSCache&#xff09;的簡單的例子&#xff0c;詳見 Spring基于注解的緩存配置--EHCache AND OSCache 現在介紹一下如何在基于注解springMVC的web應用中使用注解緩存&#xff0c;其實很簡單&#xff0…

Redis String 類型操作及常用命令

七個原則 Redis 是一個操作數據結構的語言工具&#xff0c;它提供基于 TCP 的協議以操作豐富的數據結構。在 Redis 中&#xff0c;數據結構這個詞的意義不僅表示在某種數據結構上的操作&#xff0c;更包括了結構本身及這些操作的時間空間復雜度。Redis 定位于一個內存數據庫&am…

于我,過去,現在和未來 —— 西格里夫·薩松

In me, past, present, future meet            于我&#xff0c;過去、現在和未來To hold long chiding conference              商討聚會 各執一詞 紛擾不息My lusts usurp the present tense             林林總總的 欲望&#xff0c;…

Java assert關鍵字

Java assert關鍵字 Assert 簡介 Java2在1.4中新增了一個關鍵字&#xff1a;assert。在程序開發過程中使用它創建一個斷言(assertion)。語法格式有兩種&#xff1a; assert condition; 這里condition是一個必須為真(true)的表達式。如果表達式的結果為true&#xff0c;那么斷言為…

linux 二級域名設置

首先&#xff0c;你的擁有一個有泛域名解析的頂級域名&#xff0c;例如&#xff1a; domain.com  其次&#xff0c;在 httpd.conf 中打開 mod_rewrite  之后&#xff0c;在 httpd.conf 的最后&#xff0c;添加以下內容&#xff1a;  RewriteEngine on  RewriteMap lowe…

Spring Boot @Conditional 注解

Spring Boot Conditional注解 Conditional是Spring4新提供的注解&#xff0c;它的作用是按照一定的條件進行判斷&#xff0c;滿足條件的才給容器注冊Bean。 Conditional注解定義 Target({ElementType.TYPE, ElementType.METHOD}) Retention(RetentionPolicy.RUNTIME) Documente…

計算幾何 半平面交

LA 4992 && hdu 3761 Jungle Outpost 杭電的有點坑啊。。一直爆內存&#xff0c;后來發現大白的半平面交模板那里 point *p new point[n]; line *q new line[n]這里出了問題&#xff0c;應該是在函數里面申請不了比較大的數組&#xff0c;所以爆內存。。我在全局定義…

Maven 強制導入jar包

場景 有時候因為各種原因(依賴有了&#xff0c;jar包有了)&#xff0c;項目中就是沒有這個jar包。 在需要強導的項目中創建lib文件夾&#xff0c;將需要強導的jar包訪問lib中。添加依賴$&#xff5b;pom.basedir&#xff5d;:獲取當前所在的項目目錄 $&#xff5b;pom.basedir&…

0910

我累得時候希望你能在我身邊&#xff0c;在你的懷里好好的睡一覺。轉載于:https://www.cnblogs.com/zhanzhao/p/3964175.html

《Java 高并發》03 線程的生命周期

相關概念 進程是指一個內存中運行的應用程序&#xff0c;每個進程都有自己獨立的一塊內存空間&#xff0c;一個進程中可以啟動多個線程。 一個進程是一個獨立的運行環境&#xff0c;它可以被看作一個程序或者一個應用。而線程是在進程中執行的一個任務。Java運行環境是一個包含…

OpenLayers3 online build

openlayers3使用了一個比較復雜的build工具&#xff0c;從github上下載下來的代碼中并沒有build之后的版本&#xff0c;要配置build環境又比較繁瑣&#xff0c;好在官方的example中提供了在線的版本&#xff0c;下面就是link&#xff1a; http://openlayers.org/en/v3.0.0/buil…

Mysql 必知必會(一)

文章案例所需的SQL文件&#xff0c;點擊下載 使用MySQL 進入mysql安裝目錄下的bin目錄&#xff1a; 連接Mysql&#xff1a;mysql -uroot -p123456;顯示Mysql下的所有數據庫&#xff1a;show databases;切換數據庫&#xff1a;use local;顯示數據庫下所有表名&#xff1a;show t…

design.js

//模塊式開發 var myNamespace (function () { var myPrivateVar 0;var myPrivateMethod function (foo) {console.log(foo); };return {myPublicVar : "foo",myPublicFunction : function (bar) {myPrivateVar;myPrivateMethod(bar);} }; })(); //原型模式 var…

Spring boot 整合dynamic實現多數據源

項目git地址&#xff1a;Jacob-dynamic 準備工作 # 創建數據庫db1 CREATE DATABASE db1CHARACTER SET utf8 COLLATE utf8_bin # 創建user表 CREATE TABLE user (id int(11) DEFAULT NULL,name varchar(255) DEFAULT NULL ) ENGINEInnoDB DEFAULT CHARSETutf8 # 添加數據 INSERT…

LInux 命令大全

開關機 reboot&#xff1a;重啟shutdown -h 0 或者init 0 &#xff1a;關機halt&#xff1a;關機poweroff:關機 文件的操作 ll&#xff1a;顯示文件夾詳細信息ls&#xff1a;顯示文件目錄mkdir fileName&#xff1a;創建目錄mkdir -p fileName/fileName&#xff1a;目錄cd file…

企業級業務系統開發實戰-序言

前些年一直在做微軟的解決方案實施與軟件開發的工作。在學習、項目實施、開發與管理的過程中學到了別人不少好的東西&#xff0c;也自身總結了大量的經驗&#xff0c;希望能夠通過一個系列來跟大家分享關于軟件開發方面的內容。 這個開發系列的由來是這樣的&#xff0c;兩年前作…

Could not autowire. No beans of 'JavaMailSender' type found..md

Could not autowire. No beans of JavaMailSender type found. 導入依賴 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId><version>2.1.5.RELEASE</version> </depe…

極客Web前端開發資源集錦

本周我們帶來的前端推薦包含當前熱門的bootstrap&#xff0c;html5&#xff0c;css3等技術內容和新聞話題&#xff0c;如果你還想近一步學習如何開發&#xff0c;還可以關注我們的極客課程庫&#xff0c;里面涵蓋了現代開發技術的‘學’與‘習’的全新功能。希望對大家有所幫助…