Re: [問題] 關於物件與計時器

看板Ajax作者 (冒牌費大公)時間17年前 (2008/03/12 11:58), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/4 (看更多)
※ 引述《fillano (冒牌費大公)》之銘言: : 這是scope解析問題。 : setTimeout, setInterval是window物件底下的函數,你在裡面用到this : 這個this會指到window而不是你想的地方。 : 你可以先把this傳給一個區域變數,然後在setTimeout或setInterval中用這個變數 : 例如: : addtext=function(){ : this.add=function(){ : document.getElementById('test').value+='a'; : var thisref = this; : setTimeout(thisref.add(),1000); : } : } 發現寫的有錯,黑黑,測試過以後改寫了一下,用原po的例子: (不過改了一點,讓它只跑十次) <html> <body> <input id="test" type="text" > <script> addtext=function(){ this.count = 0; this.tid = null; var ref = this; this.add=function(){ if (ref.count==0) { ref.tid = setInterval(ref.add,1000); } ref.count ++; if (ref.count > 10) { clearInterval(ref.tid); ref.count = 0; return; } document.getElementById('test').value+='a'; } } var myobj = new addtext(); myobj.add(); </script> </body> </html> -- Sapere Aude! 這就是啟蒙運動的口號! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.250.95.16
文章代碼(AID): #17rrJa1c (Ajax)
討論串 (同標題文章)
文章代碼(AID): #17rrJa1c (Ajax)