一、常用核心函數(shù)
(1) $(selector)
選擇器,可以用于選擇頁面中的標(biāo)簽對象,等價(jià)于jQuery();查看源代碼
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if (!noGlobal) {
window.jQuery = window.$ = jQuery;
}
<script src="./js/jquery-2.2.4.js"></script>
<script>
// $() 等價(jià)于 jQuery()
console.log( $("#box") )
console.log( jQuery("#box") )
</script>
(2) each()
Query`選擇了頁面標(biāo)簽對象之后,可以針對選擇的標(biāo)簽進(jìn)行遍歷處理,包含隱式迭代和顯式迭代兩種情況
// each() 隱式和顯式迭代
const $ps = $("p")
// 設(shè)置樣式:隱式迭代
// 盡管我們沒有編寫循環(huán)語法,但是jQuery底層對選擇器選擇的標(biāo)簽
// 進(jìn)行了循環(huán)遍歷完成了樣式處理;
// 不由開發(fā)人員編寫循環(huán),而是`jQuery`自身循環(huán)處理的過程:隱式迭代
// $ps.css("border-bottom", "solid 2px orangered")
// 設(shè)置樣式:顯示迭代
for (let i = 0; i < $ps.size(); i++) {
console.log(getRandColor())
$ps.eq(i).css("border-bottom", "solid 2px " + getRandColor())
}
// jQuery提供了一個(gè)可以直接遍歷選擇器標(biāo)簽的函數(shù)each()
// $ps.each(function (index, ele) {
$ps.each( (index, ele) => {
$(ele).css("border-bottom", "solid 2px " + getRandColor())
})
// jQuery提供了一個(gè)通用的迭代函數(shù)
// $.each($ps, function (index, ele) {
$.each($ps, (index, ele) => {
$(ele).css("border-bottom", "solid 2px " + getRandColor())
})
function getRandColor() {
return "#" + Math.random().toString(16).substr(2, 6)
}
(3) 插件封裝
jQuery本身雖然提供了大量插件,但是項(xiàng)目中的需求千變?nèi)f化的,不可能滿足所有情況;jQuery提供了擴(kuò)展自己功能函數(shù)的方法,讓開發(fā)人員可以制作JQuery插件
-
jQuery.fn.extend():函數(shù)級插件 -
jQuery.extend():應(yīng)用級插件
/** 自定義插件 */
// 函數(shù)插件
jQuery.fn.extend({
trim: function () {
console.log(this.text().trim(), " 插件中的this")
return this.text().trim()
}
})
// 應(yīng)用插件
jQuery.extend({
globalTrim: function (value) {
return value.toString().trim()
}
})
二、jQuery Ajax*
回顧原生js異步請求
const _http = new XMLHttpRequest()
_http.open("GET", "http://www.example.com")
_http.send()
_http.onreadystatechange = function() {
if(_http.readyState === 4 && _http.status === 200) {
// 獲取數(shù)據(jù)
const txt = _http.responseText
// DOM...
}
}
jQuery封裝了原生JS提供了異步請求操作
// 通用函數(shù)
$.ajax({
url: "http://www.baidu.com",
methods: "GET",
data: {參數(shù)數(shù)據(jù)},
success: function(res) {
console.log(res, "服務(wù)器返回的數(shù)據(jù)")
},
error: function(err) {
console.log("請求失敗")
}
})
// GET請求
$.get('http://www.baidu.com', {參數(shù)}, function(res) => {
console.log(res, "返回的數(shù)據(jù)")
})
// POST請求
$.post('http://www.baidu.com', {參數(shù)}, function(res) => {
console.log(res, "請求到的數(shù)據(jù)")
})