<!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> #zhongjiang{ width: 100px; height: 100px; background: red; } </style> </head> <body> <div id="zhongjiang"></div> <button id="J_start">開始</button> <button id="J_stop">結束</button> </body> <script type="text/javascript"> $(function(){ var a = ''; var user = []; var LIST = { init : function(){ this.getData(); this.bindEvent(); }, getData : function(){ $.ajax({ type: "POST", url: "choujiang.php", async:false, //這裏一定要有設置,下面return user,否則uer沒有值 success:function(data){ user = JSON.parse(data); } }); return user; }, startRotate : function(){ a = setInterval(function(){LIST.start()},100); $("#J_start").unbind(); }, stopRotate : function(){ clearInterval(a); $("#J_start").bind('click',function(){LIST.startRotate()}); alert($("#zhongjiang").text()); }, bindEvent : function(){ $("#J_start").bind('click',function(){LIST.startRotate();}); $("#J_stop").bind('click',function(){LIST.stopRotate();}); }, start : function() { var sum = user.length; var luckyuser = []; var rand = Math.floor(Math.random()*sum); $.each(user,function(i,n) { if (rand == i) { luckyuser = n; } }); $("#zhongjiang").empty().append(luckyuser.phone); } } LIST.init(); }) </script> </html>
採用bind方法,當點擊開始後,去掉綁定的事件,點擊暫停後,又將事件重新綁定,防止多次點擊開始進行許多次的定時操作,這樣就暫停不了了。