js实现新闻
JavaScript 实现新闻功能
获取新闻数据
使用 fetch 或 axios 从 API 获取新闻数据。例如:
fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY')
.then(response => response.json())
.then(data => displayNews(data.articles));
显示新闻列表
创建一个函数来动态生成新闻列表的 HTML:
function displayNews(articles) {
const newsContainer = document.getElementById('news-container');
newsContainer.innerHTML = articles.map(article => `
<div class="news-item">
<h3>${article.title}</h3>
<img src="${article.urlToImage}" alt="${article.title}">
<p>${article.description}</p>
<a href="${article.url}" target="_blank">Read more</a>
</div>
`).join('');
}
添加样式
为新闻列表添加基本样式:
.news-item {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 20px;
border-radius: 5px;
}
.news-item img {
max-width: 100%;
height: auto;
}
实现搜索功能
添加搜索框和事件监听器:
document.getElementById('search-btn').addEventListener('click', () => {
const query = document.getElementById('search-input').value;
fetch(`https://newsapi.org/v2/everything?q=${query}&apiKey=YOUR_API_KEY`)
.then(response => response.json())
.then(data => displayNews(data.articles));
});
添加分页功能
实现简单的分页控制:
let currentPage = 1;
function loadPage(page) {
fetch(`https://newsapi.org/v2/top-headlines?country=us&page=${page}&apiKey=YOUR_API_KEY`)
.then(response => response.json())
.then(data => {
displayNews(data.articles);
currentPage = page;
});
}
错误处理
添加错误处理逻辑:
fetch(newsUrl)
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => displayNews(data.articles))
.catch(error => {
console.error('Error:', error);
document.getElementById('news-container').innerHTML = '<p>Failed to load news. Please try again later.</p>';
});






