Console.log正确地显示了对象数组中的元素,但innerHTML却没有



Console.log(data[i].title(显示正确的输出,但当我尝试使用innerHTML显示它时,只返回一个结果

我是编码的新手,我正在做一个网络剪贴簿项目。我有一个正在运行的服务器,它可以获取NBC新闻的标题,并将数据输入到一个数组中。当我尝试使用console.log在前端显示数据时,它会返回正确的结果,但当我尝试在html页面上显示结果时,它只返回最终结果。结果如所附图像所示。

结果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="list"></div>
<input type="text" id="input"></input><br>
<button id="submit" type="submit">Submit</button><br><br>
<p id="p"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="app.js"></script>


</body>
</html>

const PORT= 8000;
const axios = require('axios')
const cheerio = require('cheerio');
const express = require('express')
const cors= require('cors');
const { html } = require('cheerio/lib/static');
// to run this use 'npm run start' in the terminal 
const url = 'https://www.nbcnews.com/';
const app = express();
app.use(cors())
app.get('/results', (req, res) => {
axios(url)
//var x = req.body.input
.then(response=> {
const article= []
const html=response.data;
const $=cheerio.load(html);
$('.alacarte__headline', html).each(function(){
const title= $(this).text()
//._13svhQIUZqD9PVzFcLwOKT styled-outbound-link
article.push({
title
})


})
res.json(article)
}).catch(err => console.log(err))
})

app.listen(PORT, () => console.log(`listening on port ${PORT}`))

const feedDisplay= document.querySelector('#list');
fetch('http://localhost:8000/results')
.then(response => {
return response.json()

})
.then(data=> {
var x= ''
for(i=0; i<data.length; i++) {

console.log(data[i].title)
document.getElementById("p").innerHTML=(data[i].title)


}

此处:document.getElementById("p").innerHTML=(data[i].title)您正在设置innerHTML的新值。这将替换以前的值。

您可以使用数组映射方法来获取所有标题的列表,然后使用数组联接方法来联接它们。

我使用了' '空间作为分隔符,但您可以将其替换为任何字符串。

const feedDisplay= document.querySelector('#list');
fetch('http://localhost:8000/results')
.then(response => {
return response.json()

})
.then(data => {
document.getElementById("p").innerHTML = data.map(d => d.title).join(' ')
}

最新更新