這是用 es6 + jq 寫的一個簡單的 tab 組件,也能夠直接 點這裏 看效果。es6
這裏採用了 es6 的新特性 class 來生成一個組件,固然,用 es5 的 prototype 也能夠模擬。dom
class Tab { constructor(opts) { this.index = opts.index || 0; this.$tabHeader = opts.header; this.$tabBody = opts.body; this.render(); this.bind(); } render() { this.$tabHeader.find("li").eq(this.index).addClass("active").siblings().removeClass("active"); this.$tabBody.find("li").eq(this.index).show().siblings().hide(); } bind() { this.$tabHeader.on("click", "li", e => { this.index = $(e.target).index(); this.render(); }); } } let tab = new Tab({ header: $(".tab-header"), body: $(".tab-body") })
constructor:ide
組件的入口是 constructor 構造函數,es5 的話能夠寫個 init 函數來代替。函數
用來初始化一些成員變量,其中 index 是值當前顯示的第幾頁,若是沒有傳值,則默認顯示第一頁。this
render:es5
根據當前 index 渲染頭部和身體。spa
第一句話是給頭部當前 index 加上 「active」 的樣式,而且去除掉其它 li 已有的 「active」樣式。prototype
第二句話是將身體當前 index 顯示出來,而且隱藏兄弟 li 元素。code
bind對象
老樣子,綁定事件。
給頭部進行事件委託,點擊任意一個 li 則改變當前 tab 組件的 index 值,而後從新調用 render 方法渲染一下。
用了箭頭函數,能夠讓做用域始終指向 Tab 這個組件,就能夠免去額外聲明一個 self 來解決做用域問題啦。
用了箭頭函數就沒有 this 了,那麼能夠 用 e.target 來獲取當前點擊的 dom 對象。
兩個知識點:
class
arrow function
若是有什麼想跟我討論的話,請私信。