記錄一下自己的除錯歷程
組件封裝經常看到這么一段代碼
$.fn.plugin = function (options) { return this.each(function (i,t) { new Fun(this, options) }); }//組件呼叫$(".div").plugin({ str: ""}).css({ "border": "1px dotted red"}).addClass('aaa');
為什么要return為什么要each?
自己除錯了一番
發現若沒有return,列印$(".div").easySlider({}) 因為這個方法沒有回傳值所以是undefined
經過return回傳,列印$(".div").easySlider({}) 回傳當前物件
若為undefined自然就不能夠進行.css()或.addClass等方法呼叫了
這時候可能又納悶了,直接return this 不就OK了么?
例如:
$.fn.easySlider = function (options) { new ShowLink(this, options) return this; } 這個時候就要說each了,??還是之前的??,倘若頁面上有N個class為div的元素呢,即:this.length>1
這里each就必然要上場了,且每個物件都要回傳,所以此段代碼無疑是最方便的寫法了:
return this.each(function () { new ShowLink(this, options) });再配合上建構式以及向物件上添加屬性和方法,差不多就是整個封裝的流程了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/34130.html
標籤:jQuery
下一篇:jQuery基礎
