#javascript
Вопрос:
Я хочу создать новостной веб-сайт, и я скопировал стиль интерфейса из начальной загрузки и включил свой javascript. когда я нажимаю на заголовок новости, в нем не отображается описание, в котором должны отображаться новости в раскрывающемся списке. По умолчанию он закрыт, и я хочу открыть его, когда нажму на заголовок
мой html-код:
<!doctype html> <html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7 AMvyTG2x" crossorigin="anonymous">
<title>Fastest news:- The Times of India</title> </head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class="container">
<h3>Top news :<span class="badge bg-secondary my-2">By Times of India</span></h3>
<hr>
<div class="accordion" id="newsAccordion">
</div>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds 3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2 xf0Uwh9KtT" crossorigin="anonymous"></script>
<script src="index.js"></script> </body>
</html>
мой код javascipt:
console.log("This is news website made using javascript");
let newsAccordion = document.getElementById("newsAccordion");
const xhr = new XMLHttpRequest();
// xhr.open('GET', "https://newsapi.org/v2/top-headlines?sources=the-times-of-indiaamp;apiKey=12f651b5941b4db4867bac2e82f64287", true);
xhr.open('GET', "news.json", true)
xhr.onload = function() {
let json = JSON.parse(this.responseText);
let articles = json.articles;
let newsHtml = "";
console.log(articles);
articles.forEach(function(element, index) {
let news = `<div class="card">
<div class="card-header" id="heading${index}">
<h2 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapse${index}"
aria-expanded="false" aria-controls="collapse${index}">
<b>Breaking News ${index 1}:</b> ${element["title"]}
</button>
</h2>
</div>
<div id="collapse${index}" class="collapse" aria-labelledby="heading${index}" data-parent="#newsAccordion">
<div class="card-body">${element.description}. <a href="${element['url']}" target="_blank" >Read more here</a> </div>
</div>
</div>`
newsHtml = news;
});
newsAccordion.innerHTML = newsHtml;
}
xhr.send();
мой файл json для данных:
{
"status": "ok",
"totalResults": 7,
"articles": [{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Rajat Pandit",
"title": "Army explores procurement of 350 light tanks for mountainous terrain after border standoff with China",
"description": "India News: The Army is now exploring the possibility of procuring 350 light tanks, which can also be transported by air, to augment its firepower in high-altitu",
"url": "http://timesofindia.indiatimes.com/india/army-explores-procurement-of-350-light-tanks-for-mountainous-terrain-after-border-standoff-with-china/articleshow/82217825.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82217908,width-1070,height-580,imgsize-264639,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T08:29:00Z",
"content": "Army explores procurement of 350 light tanks for mountainous terrain after border standoff with Chinarn<ul><li>News</li>rn<li>India News</li>rn<li>Army explores procurement of 350 light tanks for mou… [ 58 chars]"
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Times Of India",
"title": "PBKS vs MI Live Score, IPL 2021: Mumbai Indians seek consistency; Punjab Kings eye return to winning ways",
"description": "IPL Live Score: Mumbai Indians seek consistency; Punjab Kings eye return to winning ways. Stay with TOI to get IPL live score, playing 11, scorecard, highlights and ball by ball score updates of the 17th IPL match between Punjab Kings and Mumbai Indians.",
"url": "http://timesofindia.indiatimes.com/sports/cricket/ipl/live-blog/punjab-kings-vs-mumbai-indians-pbks-vs-mi-live-score-ipl-2021-17th-match-chennai/liveblog/82214950.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82214950,width-1070,height-580,imgsize-157009,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T05:44:49Z",
"content": "Ravi Bishnoi return on the cards?rnDeepak Hooda showed what he is capable of, but greater consistency would be needed from him if the team has to prosper. They bet on Australian pace imports Jhye Ric… [ 3131 chars]"
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "PTI",
"title": "Zydus Cadila gets DCGI nod for hepatitis drug for Covid-19 treatment",
"description": "India News: Drug firm Zydus Cadila on Friday said it has received restricted emergency use approval from the Indian drug regulator for the use of Pegylated Interf",
"url": "http://timesofindia.indiatimes.com/india/zydus-cadila-gets-dcgi-nod-for-hepatitis-drug-for-covid-19-treatment/articleshow/82214909.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82214921,width-1070,height-580,imgsize-98052,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T05:43:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Bloomberg",
"title": "Even record death toll may hide extent of India’s Covid crisis",
"description": "India News: Bodies piling up at crematoriums and burial grounds across India are sparking concerns that the death toll from a ferocious new Covid-19 wave may be m.",
"url": "http://timesofindia.indiatimes.com/india/even-record-death-toll-may-hide-extent-of-indias-covid-crisis/articleshow/82213444.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82213819,width-1070,height-580,imgsize-232887,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T04:41:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Dipak K Dash",
"title": "Government to provide 5 kg free food grains to poor for May amp; June",
"description": "India News: The government on Friday announced to provide 5 kg free food grains to the poor for May and June 2021. This will cover nearly 80 crore beneficiaries u",
"url": "http://timesofindia.indiatimes.com/india/government-to-provide-5-kg-free-food-grains-to-poor-for-may-june/articleshow/82213582.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82213583,width-1070,height-580,imgsize-1921513,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T04:23:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "TIMESOFINDIA.COM",
"title": "'Inappropriate': PM Modi objects to 'protocol break' during meeting; Delhi CM expresses regret",
"description": "India News: Delhi chief minister Arvind Kejriwal on Friday faced flak for sharing a live telecast of an "in-house" meeting with Prime Minister Narendra Modi where",
"url": "http://timesofindia.indiatimes.com/india/delhi-cmo-expresses-regret-over-televised-address-during-meeting-with-pm-modi/articleshow/82213159.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82213159,width-1070,height-580,imgsize-134672,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T03:54:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Times Of India",
"title": "Coronavirus in India live updates: Zydus' Virafin gets DCGI nod for Covid treatment",
"description": "In yet another grim milestone, India recorded 3.3 lakh new Covid-19 cases, and 2,263 deaths in a day. Meanwhile, active cases crossed the 24-lakh mar",
"url": "http://timesofindia.indiatimes.com/india/coronavirus-in-india-covid-19-vaccine-cases-lockdown-live-updates-23-april-2021/liveblog/82205841.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82205841,width-1070,height-580,imgsize-148788,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-22T16:20:06Z",
"content": "Zydus Cadila gets DCGI nod for hepatitis drug for Covid-19 treatmentrnMake Covid-19 vaccination affordable, accessible through Jan Aushadi scheme: IMArnThe IMA has demanded that the Covid-19 vaccine … [ 4487 chars]"
}
]
}
Ответ №1:
Bootstrap 5 имеет несколько других имен классов и наборов данных для использования, чем его предшественники. Кроме того, вы включали в себя bootstrap.js дважды на странице.
Я удалил extra .js, добавил несколько классов аккордеона и изменил эти 2 набора данных: data-bs-toggle="collapse" data-bs-target="#collapse${index}"
https://getbootstrap.com/docs/5.0/components/accordion/
console.log("This is news website made using javascript");
let newsAccordion = document.getElementById("newsAccordion");
//const xhr = new XMLHttpRequest();
let json = getJson();
let articles = json.articles;
let newsHtml = "";
console.log(articles);
articles.forEach(function(element, index) {
let news = `<div class="card">
<div class="card-header" id="heading${index}">
<h2 class="mb-0">
<button class="btn btn-link accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse${index}"
aria-expanded="false" aria-controls="collapse${index}">
<b>Breaking News ${index 1}:</b> ${element["title"]}
</button>
</h2>
</div>
<div id="collapse${index}" class="accordion-collapse collapse" aria-labelledby="heading${index}" data-parent="#newsAccordion">
<div class="card-body">${element.description}. <a href="${element['url']}" target="_blank" >Read more here</a> </div>
</div>
</div>`
newsHtml = news;
});
newsAccordion.innerHTML = newsHtml;
//xhr.send();
function getJson() {
let theJson = {
"status": "ok",
"totalResults": 7,
"articles": [{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Rajat Pandit",
"title": "Army explores procurement of 350 light tanks for mountainous terrain after border standoff with China",
"description": "India News: The Army is now exploring the possibility of procuring 350 light tanks, which can also be transported by air, to augment its firepower in high-altitu",
"url": "http://timesofindia.indiatimes.com/india/army-explores-procurement-of-350-light-tanks-for-mountainous-terrain-after-border-standoff-with-china/articleshow/82217825.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82217908,width-1070,height-580,imgsize-264639,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T08:29:00Z",
"content": "Army explores procurement of 350 light tanks for mountainous terrain after border standoff with Chinarn<ul><li>News</li>rn<li>India News</li>rn<li>Army explores procurement of 350 light tanks for mou… [ 58 chars]"
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Times Of India",
"title": "PBKS vs MI Live Score, IPL 2021: Mumbai Indians seek consistency; Punjab Kings eye return to winning ways",
"description": "IPL Live Score: Mumbai Indians seek consistency; Punjab Kings eye return to winning ways. Stay with TOI to get IPL live score, playing 11, scorecard, highlights and ball by ball score updates of the 17th IPL match between Punjab Kings and Mumbai Indians.",
"url": "http://timesofindia.indiatimes.com/sports/cricket/ipl/live-blog/punjab-kings-vs-mumbai-indians-pbks-vs-mi-live-score-ipl-2021-17th-match-chennai/liveblog/82214950.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82214950,width-1070,height-580,imgsize-157009,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T05:44:49Z",
"content": "Ravi Bishnoi return on the cards?rnDeepak Hooda showed what he is capable of, but greater consistency would be needed from him if the team has to prosper. They bet on Australian pace imports Jhye Ric… [ 3131 chars]"
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "PTI",
"title": "Zydus Cadila gets DCGI nod for hepatitis drug for Covid-19 treatment",
"description": "India News: Drug firm Zydus Cadila on Friday said it has received restricted emergency use approval from the Indian drug regulator for the use of Pegylated Interf",
"url": "http://timesofindia.indiatimes.com/india/zydus-cadila-gets-dcgi-nod-for-hepatitis-drug-for-covid-19-treatment/articleshow/82214909.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82214921,width-1070,height-580,imgsize-98052,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T05:43:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Bloomberg",
"title": "Even record death toll may hide extent of India’s Covid crisis",
"description": "India News: Bodies piling up at crematoriums and burial grounds across India are sparking concerns that the death toll from a ferocious new Covid-19 wave may be m.",
"url": "http://timesofindia.indiatimes.com/india/even-record-death-toll-may-hide-extent-of-indias-covid-crisis/articleshow/82213444.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82213819,width-1070,height-580,imgsize-232887,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T04:41:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Dipak K Dash",
"title": "Government to provide 5 kg free food grains to poor for May amp; June",
"description": "India News: The government on Friday announced to provide 5 kg free food grains to the poor for May and June 2021. This will cover nearly 80 crore beneficiaries u",
"url": "http://timesofindia.indiatimes.com/india/government-to-provide-5-kg-free-food-grains-to-poor-for-may-june/articleshow/82213582.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82213583,width-1070,height-580,imgsize-1921513,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T04:23:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "TIMESOFINDIA.COM",
"title": "'Inappropriate': PM Modi objects to 'protocol break' during meeting; Delhi CM expresses regret",
"description": "India News: Delhi chief minister Arvind Kejriwal on Friday faced flak for sharing a live telecast of an "in-house" meeting with Prime Minister Narendra Modi where",
"url": "http://timesofindia.indiatimes.com/india/delhi-cmo-expresses-regret-over-televised-address-during-meeting-with-pm-modi/articleshow/82213159.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82213159,width-1070,height-580,imgsize-134672,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-23T03:54:00Z",
"content": null
},
{
"source": {
"id": "the-times-of-india",
"name": "The Times of India"
},
"author": "Times Of India",
"title": "Coronavirus in India live updates: Zydus' Virafin gets DCGI nod for Covid treatment",
"description": "In yet another grim milestone, India recorded 3.3 lakh new Covid-19 cases, and 2,263 deaths in a day. Meanwhile, active cases crossed the 24-lakh mar",
"url": "http://timesofindia.indiatimes.com/india/coronavirus-in-india-covid-19-vaccine-cases-lockdown-live-updates-23-april-2021/liveblog/82205841.cms",
"urlToImage": "https://static.toiimg.com/thumb/msid-82205841,width-1070,height-580,imgsize-148788,resizemode-75,overlay-toi_sw,pt-32,y_pad-40/photo.jpg",
"publishedAt": "2021-04-22T16:20:06Z",
"content": "Zydus Cadila gets DCGI nod for hepatitis drug for Covid-19 treatmentrnMake Covid-19 vaccination affordable, accessible through Jan Aushadi scheme: IMArnThe IMA has demanded that the Covid-19 vaccine … [ 4487 chars]"
}
]
}
return theJson;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7 AMvyTG2x" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class="container">
<h3>Top news :<span class="badge bg-secondary my-2">By Times of India</span></h3>
<hr>
<div class="accordion" id="newsAccordion">
</div>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 2: Separate Popper and Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2 xf0Uwh9KtT" crossorigin="anonymous"></script>