2015-02-08 31 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)