JS利用取余实现toggle多函数
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> window.onload = function (){ var button = document.getElementById('button'); var onOff = 0; button.onclick = function (){ toggle( [function (){ alert(1); }, function (){ alert(2); }, function (){ alert(3); }, function (){ alert(4); } ] ); } function toggle( fns ){ /* 接收一个数组形式的函数集合 或者使用arguments形式接收参数 根据onOff的索引调用对应的函数 onOff自增 onOff取余当前数组的长度(函数的个数) onOff等于当前数组的长度onOff归0 */ fns[onOff](); onOff++; onOff%=fns.length; } } </script> </head> <body> <button id="button">toggle</button> </body> </html>