2015-02-08 30 views
0

第一個問題是當第一次單擊按鈕時不會顯示該頁面。第二個相關的問題是,當單擊按鈕第一次單擊按鈕時,出現「無法讀取未定義的屬性'innerHTML'」的錯誤,但當按鈕被單擊兩次時,一切正常。Javascript - 頁面按鈕單擊兩次後纔會顯示

main.js

var surveyPage = ''; 
var surveyQuestions = ''; 
var surveyPageData = ''; 

var fakeDiv = document.createElement('div'); 

function get_surveyPageHtml(url) { 
    $.get(url, function(data) { 
     //console.log(data); 
     surveyPage = data; 

     fakeDiv.innerHTML = ''; 
     fakeDiv.innerHTML = data; 

    }); 
    surveyQuestions = ''; 
    surveyQuestions = fakeDiv.getElementsByClassName('question'); 
    console.log(surveyQuestions); 

    surveyPageData = surveyQuestions[1].innerHTML; 
    console.log(surveyPageData); 
} 

$(document).ready(function() { 

    url = "page/page.html"; 
    $("#button").click(function(){ 

     get_surveyPageHtml(url); 
     $("#display").html(surveyPage); 

    }); 
}); 

的index.html

<!DOCTYPE html> 
<html> 
<head> 
    <title>TEST</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

    <script type="text/javascript" src="jquery-1.11.2.min.js"></script> 
    <script type="text/javascript" src="main.js"></script> 

</head> 
<body> 
    <div> 
     <button id="button">Get page data</button> 
    </div> 

    <div id="display"></div> 

</body> 
</html> 

頁/ page.html中

<h2>Survey</h2> 

<label class="question">Question 1</label> 
<label class="question">Question 2</label> 
<div class="question"> 
    Question 3 
    <label class="question">Question 4</label> 
</div> 

回答

0

的罪魁禍首,您的問題是:

get_surveyPageHtml(url); 
$("#display").html(surveyPage); 

AJAX請求需要時間,並且您正在嘗試在AJAX請求完成之前使用響應。您可以在這裏移動$("#display").html(surveyPage);解決這個問題:

//... 
$.get(url, function(data) { 
    //console.log(data); 
    surveyPage = data; 

    fakeDiv.innerHTML = ''; 
    fakeDiv.innerHTML = data; 

    $("#display").html(surveyPage); 
}) 

這樣,當Ajax響應來在頁面加載

- 編輯 -

你得到Cannot read property 'innerHTML' of undefined原因與第一個相同,只是在不同的代碼塊中。這是你應該怎麼做的:

function get_surveyPageHtml(url) { 
    $.get(url, function(data) { 
     //console.log(data); 
     surveyPage = data; 

     fakeDiv.innerHTML = ''; 
     fakeDiv.innerHTML = data; 
     $("#display").html(surveyPage); 

     surveyQuestions = ''; 
     surveyQuestions = fakeDiv.getElementsByClassName('question'); 
     console.log(surveyQuestions); 

     surveyPageData = surveyQuestions[1].innerHTML; 
     console.log(surveyPageData); 

    }); 

} 
+0

謝謝。但它並沒有解決問題的第二部分。 – JareX 2015-02-08 06:42:59

+0

已更新,以解決第二個問題。只要確保任何依賴於AJAX請求的代碼要麼直接在'.get(url,function(data){...});'中運行,或者從中調用,那麼你應該沒問題。 – Eclecticist 2015-02-08 06:51:14

0

爲了澄清一些事情,你的其他語句也應該在ajax完成後去。

$.get(url, function(data) { 

    // code... 

    surveyQuestions = ''; 
    surveyQuestions = fakeDiv.getElementsByClassName('question'); 
    console.log(surveyQuestions); 
    surveyPageData = surveyQuestions[1].innerHTML; 
    console.log(surveyPageData); 
} 

如果你使用jQuery,你的目的一個很好的做法,我建議這樣的:

http://plnkr.co/edit/Rr5UtYcHNTUf0cEMf9pc(按運行,看看main.js)