В настоящее время у меня есть веб-страница, которая получает данные об общедоступных событиях из Github API.Для каждого из данных у меня есть его, где он сгенерирует кнопку для отображения информации на странице и div для отображения дополнительной информации в качестве модальной.У меня модал скрыт по умолчанию.Я пытаюсь получить его там, где каждый раз, когда я нажимаю кнопку, появится соответствующий модал.Я попытался исследовать это, и методы, которые я нашел, просто не работают с моим кодом, и я не могу понять, почему.Я думаю, это потому, что мои элементы генерируются вместо того, чтобы жестко кодировать его в файле HTML?Я все еще новичок в JavaScript, поэтому я действительно хочу сначала придерживаться базового, и по возможности сделать это с vanillaJS.
Мой код:
function loadEvents()
{
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.github.com/events', true);
xhr.onload = function()
{
if(this.status == 200)
{
var response = JSON.parse(this.responseText);
var output = '';
var modalResult = '';
for(var i in response)
{
output +=
//I'm using the id of the events to add on to the name of data-modal as a way of matching it up to the id of the modal later
'<button class="pubEvents" data-modal="modal'+response[i].id+'">' +
'<ul>' +
'<li><b>Username:</b> '+response[i].actor.login+'</li>' +
'<li><b>Event Type:</b> '+response[i].type+'</li>' +
'<li><b>Repo:</b> '+response[i].repo.name+'</li>' +
'</ul>' +
'</button>' +
'<div id="modal'+response[i].id+'" class="bgModal">' + //The id of the modal should match with the button attribute data-modal
'<div class="modalContent">' +
'<div class="modalHeader">' +
'<span class="closeBtn">×</span>' +
'<img src="'+response[i].actor.avatar_url+'"class="avatar" width="100px" height="100px">' +
'<h2><b>'+response[i].actor.login+'</b></h2>' +
'</div>' + //modalHeader
'<div class="modalBody">' +
'<ul>' +
'<li><b>Event Type:</b> '+response[i].type+'</li>' +
'<li><b>Repo:</b> '+response[i].repo.name+'</li>' +
'</ul>' +
'</div>' + //modalBody
'<div class="modalFooter">' +
'<h2><a href="https://github.com/'+response[i].repo.name+'" target="_blank">Check out this repository here!</a></h2>' +
'</div>' + //modalFooter
'</div>' + //modalContent
'</div>' //modalBox
;
}
document.getElementById('bodyContainer').innerHTML = output;
}
}
xhr.send();
}
function refresh()
{
location.reload(true);
}
//Here is my code where I try to "connect" the modal to its respective button
//Select all the button of events
var modalBtn = document.querySelectorAll('.pubEvents');
if(modalBtn) //If modalBtn exists
{
//For each button, create an 'onclick' event
modalBtn.forEach(function(btn){
btn.onclick = function()
{
//Get the data-modal attribute of the button to "compare/match" to the id element of the modal
var modalID = btn.getAttribute('data-modal');
document.getElementById(modalID).style.display = "block";
}
});
}
body
{
font-family: Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
}
#navbar
{
float: left;
height: 120px;
width: 100%;
padding-left: 20px;
padding-right: 20px;
background-color: #4AAAA5;
color: #35404F;
}
#navbar ul li
{
list-style-type: none;
display: inline-block;
padding-left: 15px;
padding-right: 15px;
font-size: 20px;
}
#navbar ul li a
{
text-decoration: none;
}
#navbar ul li a:hover
{
color: #A3D39C;
cursor: pointer;
}
.selected
{
border: 2px solid #A3D39C;
}
.pubEvents
{
background-color: # #F0F0F0;
border: 2px solid #4AAAA5;
border-radius: 10px;
color: #35404F;
width: 100%;
font-size: 20px;
margin-top: 20px;
text-align: left;
}
.pubEvents ul li
{
list-style-type: none;
}
#bodyContainer
{
margin-left: 15px;
margin-right: 15px;
}
.pubEvents:hover
{
background-color: #A3D39C;
cursor: pointer;
}
.bgModal
{
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.8);
cursor: default;
}
.modalContent
{
background-color:#F4F4F4;
color: #35404F;
margin: 10% auto;
width:50%;
//height: 25%;
}
#modalContent ul li
{
list-style-type: none;
line-height: 1.6;
}
.modalHeader h2
{
font-size: 30px;
margin: 0;
}
.modalHeader
{
background: #4AAAA5;
padding: 15px;
height: 100px;
color: #35404F;
}
.modalBody
{
font-size: 20px;
padding: 10px 20px;
}
.modalFooter
{
background: #4AAAA5;
padding: 10px;
text-align: center;
}
.modalFooter h2
{
font-size: 25px;
}
.modalFooter a
{
color: #35404F;
text-decoration: none;
}
.modalFooter a:hover
{
color: #7CCCC5;
cursor: pointer;
}
.avatar
{
float: left;
margin-right: 20px;
}
.closeBtn
{
float: right;
font-size: 30px;
}
.closeBtn:hover
{
color: #7CCCC5;
cursor: pointer;
}
#refreshBtn
{
position: fixed;
bottom: 20px;
right: 20px;
border-radius: 10%;
background-color: #7CCCC5;
border: 2px solid #35404F;
font-size: 25px;
color: #35404F;
}
#refreshBtn:hover
{
background-color: #A3D39C;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<link href="ghDashboardCSS.css" rel="stylesheet" type="text/css">
<head>
<meta charset="utf-8">
<title>Github Dashboard</title>
</head>
<body onload="loadEvents()">
<div id="navbar">
<h1>Github Dashboard</h1>
<ul>
<li class="selected">PUBLIC EVENTS</a></li>
<li><a>PERSONAL EVENTS</a></li>
</ul>
</div>
<div id="bodyContainer">
</div>
<button id="refreshBtn" onclick="refresh()">↻<br>Refresh</button>
<script src="publicScript.js"></script>
</body
</html>