![](/img/trans.png)
[英]JavaScript/ AngularJS: Error Message displays only when I click twice the button
[英]Javascript - Page displays only after button clicked twice
第一個問題是,第一次單擊該按鈕時無法顯示該頁面。 第二個相關問題是,第一次單擊按鈕時出現錯誤“無法讀取未定義的屬性'innerHTML'的定義”,盡管單擊按鈕兩次后一切都很好。
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>
您問題的元凶是:
get_surveyPageHtml(url);
$("#display").html(surveyPage);
AJAX請求需要一些時間,因此您嘗試在AJAX請求完成之前使用響應。 您可以通過移動$("#display").html(surveyPage);
來解決此問題$("#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);
});
}
為了澄清一些問題,在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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.