jQuery 進(jìn)階

一、常用核心函數(shù)
(1) $(selector)
選擇器,可以用于選擇頁(yè)面中的標(biāo)簽對(duì)象,等價(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`選擇了頁(yè)面標(biāo)簽對(duì)象之后,可以針對(duì)選擇的標(biāo)簽進(jìn)行遍歷處理,包含隱式迭代和顯式迭代兩種情況

// each() 隱式和顯式迭代
const $ps = $("p")
// 設(shè)置樣式:隱式迭代
// 盡管我們沒有編寫循環(huán)語(yǔ)法,但是jQuery底層對(duì)選擇器選擇的標(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ù)級(jí)插件
  • jQuery.extend():應(yīng)用級(jí)插件
/** 自定義插件 */
// 函數(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異步請(qǐng)求

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提供了異步請(qǐng)求操作

// 通用函數(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("請(qǐng)求失敗")
  }
})
// GET請(qǐng)求
$.get('http://www.baidu.com', {參數(shù)}, function(res) => {
      console.log(res, "返回的數(shù)據(jù)")
 })
// POST請(qǐng)求
$.post('http://www.baidu.com', {參數(shù)}, function(res) => {
       console.log(res, "請(qǐng)求到的數(shù)據(jù)")
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容