2017-05-20 49 views
1

我想從使用JSON和AJAX的API打印對象,它在我使用console.log進行查看時起作用。但我的generateCreatureDiv函數由於某些原因不起作用。我的JavaScript代碼不顯示預期的結果

這是我的代碼:

$(document).ready(function() { 
 
    var xhttp = new XMLHttpRequest(); 
 
    xhttp.onreadystatechange = function() { 
 
    if (this.readyState == 4 && this.status == 200) { 
 
     var response = this.responseText; 
 
     var creatureData = JSON.parse(response); 
 
     console.log(creatureData); 
 

 
     // get a creature from the data 
 

 
     for (var i = 0; i < creatureData.creatures.length; i++) { 
 
     var creature = creatureData.creatures; 
 
     console.log(creature[i]); 
 
     document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]); 
 
     } 
 

 
     function generateCreatureDiv(creature) { 
 
     var CreatureDiv = $("<div />"); 
 
     console.log("hoe"); 
 
     CreatureDiv.id = "CreatureInfo"; 
 
     console.log("hoe") 
 
     $("CreatureDiv").append("<h1>" + creature.name + "</h1>"); 
 
     console.log("hoe"); 
 
     $("CreatureDiv").append("<img>" + creature.image + "</img>"); 
 
     return CreatureDiv; 
 
     console.log("hoe"); 
 

 
     } 
 

 
     // create a select option for the object 
 
     // Have a 
 

 

 
    } 
 

 
    }; 
 

 
    xhttp.open("GET", "https://api.myjson.com/bins/17f3jl", true); 
 
    xhttp.send(); 
 

 

 

 
});
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <script src="./jquery-3.1.1.min.js"></script> 
 
    <script src="./script.js"></script> 
 
    <script src="./stylesheet.css"></script> 
 
    <meta charset="utf-8"> 
 
    <title></title> 
 
    </head> 
 
    <body> 
 
    <div id="CreatureEntry"> 
 
     <select id="SelectOption"> 
 
     
 
     </select> 
 
    </div> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    </body> 
 
</html>

+1

你是什麼意思的「不工作」?這是一個很糟糕的問題描述。你能指望什麼?究竟發生了什麼?任何錯誤? – DigiFriend

回答

0

刪除$("CreatureDiv")。其在"報價不與你的代碼中的任何ID或Class.And選擇與var CreatureDiv = $("<div />");。所以變化已經申報像這樣

function generateCreatureDiv(creature) { 
     var CreatureDiv = $("<div />"); 
     console.log("hoe"); 
     CreatureDiv.id = "CreatureInfo"; 
     console.log("hoe") 
     $(CreatureDiv).append("<h1>" + creature.name + "</h1>"); 
     console.log("hoe"); 
     $(CreatureDiv).append("<img>" + creature.image + "</img>"); 
     return CreatureDiv; 
     console.log("hoe"); 

     } 

而且像這樣改變

document.getElementById("CreatureEntry").innerHTML += generateCreatureDiv(creature[i]); 

,而不是

document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]); 

因爲innerHTML =generateCreatureDiv(creature[i]);它將在每次調用

0

此行是清除所有的DIV的內容,爲您的陣列中的每個元素重置前值:

document.getElementById("CreatureEntry").innerHTML = generateCreatureDiv(creature[i]); 

刪除第一部分,只是調用你的方法並追加結果?

$("CreatureEntry").append(generateCreatureDiv(creature[i])); 

另外,你需要的地方你引用$("CreatureDiv")刪除引號並使用$(CreatureDiv)

+0

非常感謝。我是初學者,所以這些錯誤中有些對我來說是新的。我感謝您的幫助 –