Home >Web Front-end >JS Tutorial >A simple example of tab development (code)
This article brings you a simple example (code) of tab development. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The following methods are used
changeTabHandle function used in methods 1-3
//当前点击按钮的索引 function changeTabHandle(n) { for(var i=0; i<tabList.length; i++){ tabList[i].className = ''; pList[i].className = ''; } tabList[n].className = 'active'; pList[n].className = 'active'; }
Custom attribute name
//方法一:自定义属性方法 console.log(tabList); for (var i = 0;i < tabList.length; i++){ tabList[i]._f_index = i; tabList[i].onclick = function () { console.dir(this); changeTabHandle(this._f_index); } }
es6 let
//方法二:var --> let for(let i=0; i<tabList.length; i++){ tabList[i].onclick = function() { changeTabHandle(i); } }
Closure
Method 1:
for(var i=0; i<tabList.length; i++){ ~function (i) { tabList[i].onclick = function () { changeTabHandle(i); } }(i) }
Method 2:
for(var i=0; i<tabList.length; i++){ tabList[i].onclick = function (i) { return function() { changeTabHandle(i); } }(i) }
Remember which one was selected last time instead of clearing all custom attributes
beforeIndex = 0; for(var i=0; i<tabList.length; i++){ tabList[i]._f_index = i; tabList[i].onclick = function() { tabList[beforeIndex].className = ''; pList[beforeIndex].className = ''; tabList[this._f_index].className = 'active'; pList[this._f_index].className = 'active'; beforeIndex = this._f_index; } }
Memory last time it was the one that was selected instead of clearing all let
for(let i=0; i<tabList.length; i++){ tabList[i].onclick = function (params) { tabList[beforeIndex].className = ''; pList[beforeIndex].className = ''; tabList[i].className = 'active'; pList[i].className = 'active'; beforeIndex = i; } }
github example code https://github.com/fung-yu/js... Tab chapter
The above is the detailed content of A simple example of tab development (code). For more information, please follow other related articles on the PHP Chinese website!