首頁  >  文章  >  web前端  >  即將發布的jQuery 3 有哪些新功能_jquery

即將發布的jQuery 3 有哪些新功能_jquery

WBOY
WBOY原創
2016-05-16 15:05:371077瀏覽

jQuery 的橫空出世,至今已有十個年頭了,而它的長盛不衰顯然不是沒有理由的。 jQuery是繼prototype之後又一個優秀的Javascript函式庫。它是輕量級的js庫,它相容於CSS3,也相容於各種瀏覽器(IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+),jQuery2.0及後續版本將不再支援IE6/7 /8瀏覽器。 jQuery讓用戶能更方便地處理HTML(標準通用標記語言下的一個應用程式)、events、實作動畫效果,並且方便地為網站提供AJAX互動。 jQuery還有一個比較大的優點是,它的文件說明很全,而且各種應用也說得很詳細,同時還有許多成熟的插件可供選擇。

在未來的幾週內,jQuery 就將抵達一個重要的里程碑——正式發布 3.0 版本。 jQuery 3 修復了大量的 bug,增加了新的方法,同時移除了一些接口,並修改了少量接口的行為。在這篇文章中,我將為大家專注於講解 jQuery 3 所引入的那些最重要的變化。

新增特性

我們先來討論 jQuery 3 中最重要的幾個新增特性。

for...of 循環

在 jQuery 3 中,我們可以用 for...of 迴圈語句來迭代一個 jQuery 集合中的所有 DOM 元素。這種新的迭代方法是 ECMAScript 2015(即 ES6)規範中的一部分。這個方法可以對 「可迭代物件」(例如 Array、Map、Set 等)進行循環。

當使用這種新的迭代方法時,你在循環體內每次拿到的值並不是一個 jQuery 對象,而是一個 DOM 元素(譯註:這一點跟 .each() 方法類似)。當你在對一個 jQuery 集合進行操作時,這個新的迭代方法可以少許改善你的程式碼。

為了搞清楚這種迭代方法到底是怎麼運作的,我們來假設一個場景-你需要為頁面中的每個 input 元素分配一個 ID。在 jQuery 3 之前,你可能會這樣寫:

複製程式碼 程式碼如下:
var $inputs = $('input');for(varvar i = 0; i    $inputs[i].id = 'input-' + i;
}

而在 jQuery 3 中,你就可以這樣寫了:

複製程式碼 程式碼如下:
var $inputs = $('input');var i = 0 ;
for(var input of $inputs) {
   input.id = 'input-' + i++;
}

(譯註:其實 jQuery 自己是有個 .each() 方法的,可讀性也不賴。)

$.get() 和 $.post() 函數的新簽章

jQuery 3 為 $.get() 和 $.post() 這兩個工具函數增加了新簽名,從而使得它們和 $.ajax() 的介面風格保持一致。新簽名是這樣的:

複製程式碼 程式碼如下:
$.get([settings])
$.post([settings])

settings 是一個對象,它包含多個屬性。它的格式和你以前傳給 $.ajax() 的參數格式是一樣的。如果你想更清楚地了解這個參數對象,請參考 $.ajax() 頁面 中的相關描述。

$.get() 和 $.post() 的參數物件與傳給 $.ajax() 的參數相比,唯一的差異就是前者的 method 屬性總是會被忽略。原因其實也很簡單,$.get() 和 $.post() 本身就已經預設了發起 Ajax 請求的 HTTP 方法了(顯然 $.get() 就是 GET,而 $.post() 就是 POST)。也就是說,正常人類應該是不會想用 $.get() 方法來傳送一個 POST 請求的。

假設有以下一段程式碼:

複製程式碼 程式碼如下:
$.get({
    url: 'https://www.audero.it',
    method: 'POST' // This property is ignored
                   // 此屬性被忽略});

No matter what we write the method attribute as, this request will always be sent as GET.

Use requestAnimationFrame() to implement animation

All modern browsers (including IE10 and above) support requestAnimationFrame. jQuery 3 will use this API internally to implement animations to achieve smoother, more resource-efficient animation effects.

unwrap() method

jQuery 3 adds an optional selector parameter to the unwrap() method. The new signature of this method is:

Copy code The code is as follows:
unwrap([selector])

With this feature, you can pass this method a string containing a selector expression and use it to match within the parent element. If there is a matching child element, the parent layer of this child element will be lifted; if there is no match, no operation will be performed.

Changed features

jQuery 3 also changes the behavior of some features.

:visible and :hidden

jQuery 3 will change the meaning of :visible and :hidden filters. As long as the element has any layout box, even if the width and height are zero, it will be considered :visible. For example, br elements and inline elements without content are now selected by the :visible filter.

So if your page contains the following structure:

Copy code The code is as follows:

Then run the following statement:

Copy code The code is as follows:
console.log($('body :visible').length) ;

In jQuery 1.x and 2.x, you would get 0; but in jQuery 3, you would get 2.

data() method

Another important change is related to the data() method. Its behavior is now consistent with the Dataset API specification. jQuery 3 will convert all property key names to camelCase. Let’s take a closer look, taking the following element as an example:

Copy code The code is as follows:

When we are using versions prior to jQuery 3, if we run the following code:

Copy code The code is as follows:
var $elem = $('#container');
$elem.data({ 'my-property': 'hello'});console.log($elem.data());

You will get the following results in the console:

Copy code The code is as follows:
{my-property: "hello"}

In jQuery 3, we will get the following results:

Copy code The code is as follows:
{myProperty: "hello"}

請注意,在 jQuery 3 中,屬性名稱已經變成了駝峰形式,橫槓已經被移除了;而在先前的版本中,屬性名稱會保持全小寫,並原樣保留橫槓。

Deferred 物件

jQuery 3 也改變了 Deferred 物件的行為。 Deferred 物件可以說是 Promise 物件的前身之一,它實現了對 Promise/A+ 協定 的相容。這個物件以及它的歷史都相當有趣。如果想要深入了解,你可以去閱讀 jQuery 官方文檔,也可以去看我寫的書《jQuery 實戰(第三版)》——這本書也涵蓋了 jQuery 3。

在jQuery 1.x 和2.x 中,傳給Deferred 的回呼函數內如果出現未捕獲的異常,會立即中斷程序的執行(譯註:即靜默失敗,其實jQuery 絕大多數回調函數的行為都是這樣的)。而原生的 Promise 物件並非如此,它會拋出異常,並不斷向上冒泡,直至到達 window.onerror(通常冒泡的終點是這裡)。如果你沒有定義一個函數來處理這個錯誤事件的話(通常我們都不會這麼做),那麼這個異常的資訊將會被顯示出來,此時程式的執行才會停止。

jQuery 3 將會遵循原生 Promise 物件的模式。因此,回呼內產生的異常將會導致失敗狀態(rejection),並觸發失敗回呼。一旦失敗回呼執行完畢,整個進程就會繼續推進,後續的成功回呼將會被執行。

為了讓你更能理解這個差異,讓我們來看一個小例子。例如我們有以下程式碼:

複製程式碼 程式碼如下:
var deferred = $.Deferred();

var deferred = $.Deferred();
deferred
  .then(function() {    throw new Error('An error');
  })
  .then(    function() {      console.log('Success 1');
    },    function() {      console.log('Failure 1');
    }
  )
  .then(    function() {      console.log('Success 2');
    },    function() {      console.log('Failure 2');
    }
  ); deferred.resolve();

在 jQuery 1.x 和 2.x 中,只有第一個函數(也就是拋出錯誤的那個函數)會被執行到。此外,由於我們沒有為 window.onerror 定義任何事件處理函數,控制台將會輸出 “Uncaught Error: An error”,而且程式的執行將中止。

而在 jQuery 3 中,整個行為是完全不同的。你將在控制台中看到 “Failure 1” 和 “Success 2” 兩個訊息。那個異常將會被第一個失敗回調處理,並且,一旦異常得到處理,那麼後續的成功回呼將會被呼叫。

SVG 文件

沒有哪一個 jQuery 版本(包括 jQuery 3)曾官方宣稱支援 SVG 文件。不過事實上有很多方法是可以奏效的,此外還有一些方法在以前是不行的(例如操作類別名稱的那些方法),但它們在 jQuery 3 中也得到了更新。因此,在 jQuery 3 中,你應該可以放心使用諸如 addClass() 和 hasClass() 這樣的方法來操作 SVG 文件了。

已廢棄、已移除的方法和屬性

在增加了上述改進的同時,jQuery 也移除、廢棄了一些特性。

廢棄 bind()、unbind()、delegate() 和 undelegate() 方法

jQuery 在很久以前就引入了 on() 方法,它提供了一個統一的接口,用以取代 bind()、delegate() 和 live() 等方法。同時,jQuery 也引進了 off() 這個方法來取代 unbind()、undelegated() 和 die() 等方法。從那時起,bind()、delegate()、unbind() 和 undelegate() 就已經不再推薦使用了,但它們還是一直存在著。

jQuery 3 終於開始將這些方法標記為 「廢棄」 了,並計劃在未來的某個版本(很可能是 jQuery 4)中將它們徹底移除。因此,請在你的專案中統一使用 on() 和 off() 方法,這樣你就不用擔心未來版本的變更了。

移除 load()、unload() 和 error() 方法

jQuery 3 徹底拋棄了 load()、unload() 和 error() 等已經標記為廢棄的方法。這些方法在很早以前(從 jQuery 1.8 開始)就已經被標記為廢棄了,但一直沒有去掉。如果你正在使用的某款外掛程式仍然依賴這些方法,那麼升級到 jQuery 3 會把你的程式碼搞掛。因此,在升級過程中請務必留意。

移除 context、support 和 selector 屬性

jQuery 3 徹底拋棄了 context、support 和 selector 等已經標記為廢棄的屬性。同上,升級到 jQuery 3 時,請留意你正在使用的插件。

已修復的 Bug

jQuery 3 修正了以往版本中的一些非常重要的 bug。在本節中,我將著重介紹其中兩處,因為這兩者應該會對你寫程式碼的習慣帶來顯著影響。

width() 和 height() 的回傳值將不再取整

jQuery 3 修正了 width()、height() 和其它相關方法的一個 bug。這些方法的傳回值將不再捨入取整,因為這種取整行為在某些情況下不便於對元素進行定位。

我們來詳細看一看。假設你一個寬度為 100px 的容器元素,它包含了三個子元素,寬度皆為三分之一(即 33.333333%):

複製程式碼 程式碼如下:

  
My name

  
is

  
Aurelio De Rosa

在 jQuery 3 先前的版本中,如果你嘗試透過以下程式碼來取得子元素的寬度…

複製程式碼 程式碼如下:
$('.container div').width(>
$('.container div').width();

…那麼你得到結果將會是 33。原因在於 jQuery 會把 33.33333 這個值取整。而在 jQuery 3 中,這個 bug 已經被修復了,因此你將會得到更精確的結果(即一個浮點數)。

wrapAll() 方法

jQuery 3 也修正了 wrapAll() 方法中的一個 bug,這個 bug 出現在把一個函數當作參數傳給它的情況下。在 jQuery 3 先前的版本中,當一個函數傳給 wrapAll() 方法時,它會把 jQuery 集合中的每個元素單獨包裝起來。換句話說,這種行為和把一個函數傳給 wrap() 時的行為是完全一樣的。

在修復這個問題的同時,也引入了另一個變更:由於在 jQuery 3 中,這個函數只會呼叫一次了,那就無法把 jQuery 集合中每個元素都傳給它。因此,這個函數的執行上下文(this)將只能指向目前 jQuery 集合中的第一個元素。

如何下載 jQuery 3 beta 1

既然你已經讀到了這裡,那就表示你很可能想試試 jQuery 3 的第一個 beta 測試版。你可以透過以下兩個位址來取得這個版本:

    未壓縮版: https://code.jquery.com/jquery-3.0.0-beta1.js

    壓縮版: https://code.jquery.com/jquery-3.0.0-beta1.min.js

當然,你也可以透過 npm 來下載:

[code]npm install jquery@3.0.0-beta1[/code]

結論

很多人一直在唱衰敗 jQuery,說它在現代網頁開發中已經沒有一席之地了。但不管怎樣,jQuery 的開發仍在繼續,客觀的統計數據(在排名前一百萬名的網站中佔有率高達 78.5%)也讓這些論調不攻自破。

在本文中,我已經帶你了解了一次 jQuery 3 將會帶來的一些重大變化。或許你已經察覺到了,這個版本並不太可能搞掛你的既有項目,因為它引入的破壞性變更其實寥寥無幾。不過,在升級到 jQuery 3 的過程中,你還是有必要牢記一些關鍵點,例如 Deferred 物件的改進等等。同樣,在升級某個第三方函式庫時,也有必要檢查一下該專案的兼容性情況,以便儘早發現任何非預期行為,避免某些功能失效。

譯註

除了本文所提及的變更之外,jQuery 3.0 最大的變化就是徹底放棄對 IE8 的支援。 jQuery 團隊做出這個決定的原因在於,微軟已經在今年年初宣布停止對 IE 8~10 的支援。因此,jQuery 在 3.0 alpha 階段所發布的 jQuery Compat 專案也就沒有繼續存在的必要了。

不過,由於 IE8 仍然是中國大陸最受歡迎的瀏覽器之一,對國內的開發者來說,在短期(甚至中期)內還不得不停留在 jQuery 1.x 版本。

好吧,最後還是說個好消息吧。為協助使用者平滑升級,此次 jQuery 同樣會為 3.0 版本提供遷移插件(jQuery Migrate plugin)。在把jQuery 升級到3.0 之後同時運行這個插件,即可確保基於jQuery 1.x 或2.x 的既有業務代碼正常運行;同時,它還將在控制台向你報告既有代碼與jQuery 3 不相容的地方。當你修復了這些不相容問題之後,就可以安全地移除這個插件了。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn