2013-07-04 124 views
1

我想通過使用ajax一段時間後加載一個php文件。我試圖做的是一種測驗。我想讓用戶看到圖像屏幕3秒鐘,然後看到答案選項。我想連續做3次或4次。例如; 1)問題圖片 幾秒鐘後 2)答案選擇 點擊答案後 3)第二個問題圖片 ...繼續這個順序。隨着時間改變div內容

我可以用下面的代碼做到這一點:

<script type="text/javascript"> 

var content = [ 
    "<a href='resim1a.php'> link 1 </a>", 
    "<a href='resim2a.php'> link 2 </a>", 
    "insert html content" 
]; 
var msgPtr = 0; 
var stopAction = null; 

function change() { 
    var newMsg = content[msgPtr]; 
    document.getElementById('change').innerHTML = 'Message: '+msgPtr+'<p>'+newMsg; 
    msgPtr++; 
    if(msgPtr==2) 
    clearInterval(stopAction); 
} 

function startFunction() { change(); stopAction = setInterval(change, 500); } 
window.onload = startFunction; 
</script> 

<div id="change" style="border:5px solid red;width:300px; height:200px;background-Color:yellow"> </div> 

但是,當這個文件被其他文件包括在內,這個腳本不起作用。我怎樣才能使它工作?

<script type="text/javascript"> 
    function load(thediv, thefile){ 
     if (window.XMLHttpRequest){ 
     xmlhttp = new XMLHttpRequest(); 
    } else { 
     xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP'); 
     } 
     xmlhttp.onreadystatechange = function(){ 
     if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ 
     document.getElementById(thediv).innerHTML = xmlhttp.responseText; 
     } 
    } 
    xmlhttp.open('GET', thefile , true); 
    xmlhttp.send(); 
    } 
    </script> 

上一頁腳本在上面。我用這個腳本與下面的代碼:

<div id="anotherdiv" > 
     <input type="image" onclick="load('anotherdiv' , 'include.php');"src="buton1.png"> 
</div> 
+1

「包含」是什麼意思?包含在''-tags中,通過php包含,稍後通過ajax包含?它可能不起作用的原因是窗口已經加載,所以將startFunction附加到它將永遠不會被調用。 – luk2302

+0

我編輯了這個問題。其實,你說得對,窗口已經加載了,所以不會再次加載。我怎樣才能找到我的問題的替代方案?感謝您的回答... – Halil

+0

直接調用它只是因爲給出的答案建議。 – luk2302

回答

0

的原因是因爲你期望的窗口火onload事件:

的window.onload = startFunction;

ajax運行時加載窗口,爲什麼不直接調用函數?

startFunction(); 

如果您需要的腳本之前的一些DOM元素,只是把腳本的DOM元素下方,將運行該腳本後的DOM已準備就緒。

+0

startFunction();不起作用... – Halil

-1

你需要從function startFunction()

刪除change();這裏是完整的例子click here

我希望它會幫助你的。

+0

只是「不」。他爲什麼需要這樣做? – luk2302

+0

對不起,不明白! –

+0

呼籲改變的目的和工作。 – luk2302