const app = document.getElementById('root');
const container = document.createElement('div');
container.setattribute('class','container');
app.appendChild(container);
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest();
***我正在学习javascript sintaxe,例如如何使用DOM,等等!我是新手,所以如果您能详细解释一下,我将不胜感激! 在这里,我只是选择第一页,我可以考虑一种实现方法,但是很难编写代码。如果没有问题,您可以提出一些额外的建议来学习吗?我已经在进行freecodecamp。
var page = 1;
// Open a new connection,using the GET request on the URL endpoint
request.open('GET','https://api.punkapi.com/v2/beers?page='+page+'&per_page=80',true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400){
// Log each beer's name
data.forEach(beer => {
// Create a div with a card class
const card = document.createElement('div');
card.setattribute('class','card');
//Create an image and set the image content to the beer's image
const image = document.createElement('img');
image.src=beer.image_url;
// Create an h1 and set the text content to the beer's name
const h1 = document.createElement('h1');
h1.textContent = beer.name;
// Create a p and set the text content to the beer's description
const p = document.createElement('p');
beer.tagline = beer.tagline.substring(0,300);// Limit to 300 chars
p.textContent = `${beer.tagline}...` // End with an ellipses
// Append the cards to the container element
container.appendChild(card);
// Each card will contain an image,h1 and a p
card.appendChild(image);
card.appendChild(h1);
card.appendChild(p);
});
} else {
textContent('error');
}
}
// Send request
request.send();