jQuery 的 data() vs attr() 之不同

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
776   0  
·
2018/03/13
·
2 mins read


現在的網頁開發已經離不該 JavaScript 了,JavaScript 開發的人大概都是用各自喜歡的開發平台,每天網路上的談論都是那個新平台好,那個不老,應該要學那個,最近最不熱門的應該就是 jQuery 了,很多人也已經棄船不用 jQuery 了,我倒是覺得 jQuery 很好啊,最大的理由就是,到處都找得到使用的教學與問題解答,這就是老東西的好處!

最近在開發一個與網頁上 DOM 更新有密切關係的程式,其中要大量的更新 data-xx 的值,我就有一個問題,該用 JQ 的 .data() 還是 .attr() 呢?我其實裡兩個都可以用,但是我想要知道這兩個到底有什麼不同?拖 jQuery 這老東西的好處,網路上的教學很多,我就把它記下來,應該對有用到的讀者也有幫助。

  • 讀取與設定:差不多,data() 少寫幾個字,attr() 內容一定會轉成字串
    • data() 讀:$('#selector').data('index') ,設定:$('#selector').data('index',  123) 
    • attr() 讀:$('#selector').attr('data-index'),設定:$('#selector').attr('data-index',  123) 
  • 效率:都不差,參考這篇,簡單說,照這篇文章的數字,attr() 一定慢,data() 約是 1.2~4 倍的速度差別,但是如果各位真的執行這個 benchmarking,會很驚訝的發現,數字很不同,有的 attr() 會比 data() 快,不過,我覺得不用擔心效率,應為就算是最慢的,以現在的桌機,也有每秒百萬次更新的速度。
  • 相容度:完全不相容,用 data() 設的資料,attr() 讀不出來,相反也是;事實是,jQuery 是用自己的內部變數來儲存 data() 的,也就是說,要從一而終,一旦用 data() 就一路只能用到底,如果其他 JavaScript 用 attr 來讀取用 data() 設的值,一定錯得很慘。
  • 除錯:attr() 好多了,它會立即更新 DOM 的內容,所以你看得到,data() 完全不會跟新,它只更新自己內部的變數,所以網路上有人以 jQuery 的秘密來稱呼它。

總結,兩個是不同的東西,要是問我,我會用 attr() ,畢竟相容性與易於除錯實在太重要了,但是不要忘記,attr 就是只能存字串!


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

分類於:
標籤:
日期:
創作於:2018/03/13,最後更新於:2019/08/17。
合計:566字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.