我正在尝试从我的Restful api中获取内容并将其附加到html文件,但不会创建新的文章标签。主标记存在,并确认responseContent实际包含值。有什么想法为什么这段代码不起作用?
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
responseArray = JSON.parse(this.responseText);
var anchorElement = document.getElementsByTagName("main")[0];
for(var index = 0; index < responseArray.length; index++){
//tried replacing appendChild with += as well
anchorElement.appendChild(createLayout(responseArray[index]));
}
}
}
function createLayout(responseContent){
console.log(responseContent);
var article = document.createElement("article");
var header = document.createElement("header"), h4 =
document.createElement("h4");
//header.textContent = responseContent.title;
h4.textContent = "Title of event";
header.appendChild(h4);
var paragraph = document.createElement("p");
paragraph.textContent = responseContent.date + " " + responseContent.time;
console.log("article: " + article);
return article;
}
答案 0 :(得分:1)
您忘了将创建的h4和p附加到文章
HouseholdNode
现在你的方式,你的函数只返回创建的function createLayout(responseContent){
console.log(responseContent);
var article = document.createElement("article");
var header = document.createElement("header"), h4 =
document.createElement("h4");
//header.textContent = responseContent.title;
h4.textContent = "Title of event";
header.appendChild(h4);
var paragraph = document.createElement("p");
paragraph.textContent = responseContent.date + " " + responseContent.time;
console.log("article: " + article);
// missing
article.appendChild(h4);
article.appendChild(paragraph);
// __________
return article;
}
元素 - 基本上像
article
答案 1 :(得分:0)
我不知道如果我做得好,我假设您希望将文章标签包含在您的HTML中。
在您准备好将文章包含在自己的页面中之后,您将无法致电:document.body.appendChild(article);
。
如果您想header
article
,请拨打article.appendChild(header);
最后会给出类似的东西
var article = document.createElement("article");
var header = document.createElement("header"), h4 =
document.createElement("h4");
//header.textContent = responseContent.title;
h4.textContent = "Title of event";
header.appendChild(h4);
console.log(header);
var paragraph = document.createElement("p");
paragraph.textContent = responseContent.date + " " + responseContent.time;
article.appendChild(header); //if you would like to append header to article
console.log(article);
document.body.appendChild(article); //if you would like to append article to <body></body>
希望这会有所帮助,如果我误解了某些内容,请告诉我