这是用 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
若是有什么想跟我讨论的话,请私信。