2014-03-31 31 views
-2

我是一個Javascript初學者。爲什麼不彈出()增量變量c?

爲什麼c每次都會上去popup()被調用?

我用document.write,看它是否會上漲,但它保持與1

<script> 

    var c = 0; 



window.onload=function() 
{ 
    var myVar = setInterval('popup()',2000); 

    c++; 
    document.write(c); 
    if(c>2) 
    { 
    clearInterval(myVar); 
    } 
} 

function popup() 
{ 
    alert('hallo'); 

} 

</script> 

代碼中間隔不會C> 2後停止。

<script> 

var c = 0; 
var myVar = null; 

window.onload=function() 
{ 
    myVar = setInterval('popup()',2000); 
} 

function popup() 
{ 
    alert('hallo'); 
    c++; 
    document.write(c); 
    if(c>2) 
    { 
     clearInterval(myVar); 
    } 
} 

</script> 

回答

1

在加載頁面時,調用setInterval。

因此,每隔兩秒鐘,您將調用彈出功能,其中顯示'hallo'。

然後,你增加你的變量,等...

=>讓你的c變量遞增,在彈出的功能,增加它。

編輯: 要回答一個更好的佈局註釋:你需要提高下,在你的函數

setInterval() returns an interval ID, which you can pass to clearInterval(): 

var refreshIntervalId = setInterval(fname, 10000); 

/* later */ 

clearInterval(refreshIntervalId); 
+0

謝謝,但現在我有其他的問題。 我的間隔將不會停止後c> 2 – user3406286

+0

加入檢查的功能;-) – Elfentech

+0

嗨,是的,我做了,但它仍然無法正常工作,對不起,人真的很簡單的問題! – user3406286

1

function popup() 
{ 
    alert('hallo'); 
    c++; 
} 
0

你的window.onload函數被調用一次當頁面加載時。您必須在彈出的功能

var c = 0; 
var myVar = null; 

window.onload=function() 
{ 
    myVar = setInterval('popup()',2000); 
} 

function popup() 
{ 
    alert('hallo'); 
    c++; 
    document.write(c); 
    if(c>2) 
    { 
     clearInterval(myVar); 
    } 
} 
+0

嗨感謝您的答覆,但現在我的間隔即使在c> 2後也不會停止。 – user3406286

1

遞增支票C在window.onload,你調用setInternal方法,你在呼喚popup功能。 因此,您需要增加並在popup函數中打印c。此外,clearInterval也需要在popup函數中調用。

<script> 
    var c = 0, 
     myVar; 
    window.onload = function() { 
     myVar = setInterval(popup, 2000); 
    } 

    function popup() { 
     //alert('hello'); 
     c++; 
     document.write(c); 
     if (c > 2) { 
      clearInterval(myVar); 
     } 
    } 
</script> 

的jsfiddle:http://jsfiddle.net/jaNjn/