我正在开发一个时间轴类型的app / page,并希望在单击“Read More”时打开每个时间轴块内容的模态窗口。但是,我似乎在迭代阶段迷失了,因为每当我点击“阅读更多”时,只有最后一部分的标题出现在模态标题中。这意味着循环完成迭代并使用最后一个元素填充模态标题。任何见解将不胜感激!
**将完整的程序编辑成更易消化的格式(希望如此)**
//select modal interaction
var readBtn = document.getElementsByClassName("cd-read-more");
var closeBtn = document.querySelector(".closeBtn");
var modal = document.querySelector(".modal");
var modalTitle = document.getElementById("modal-title");
var modalBody = document.querySelector(".modal-body");
var contentBlock = document.getElementsByClassName("cd-timeline-block")
var timeline = [];
//select cd-timeline-content
timeline.postTitles = document.getElementsByClassName("post-title");
timeline.postBody = document.getElementsByClassName("post-body");
timeline.postImg = document.getElementsByClassName("pic");
//modal event functions
function openModal(indexNumber) {
for (var i = 0; i < readBtn.length; i++) {
modalTitle.innerHTML = timeline.postTitles[i].innerHTML;
}
modal.style.display = "block";
};
//event listeners for selections
//loop thru collection of readBtn array and call openModal to each
for (var i = 0; i < readBtn.length; i++) {
readBtn[i].addEventListener("click", openModal);
};
<!doctype html>
<title>Example Timeline</title>
</head>
<body>
<header>
<h1>Example Timeline</h1>
</header>
<section id="cd-timeline" class="cd-container">
<div class="cd-timeline-block">
<div class="cd-timeline-img cd-location">
<img src="img/cd-icon-location.svg" alt="Picture">
</div>
<!-- cd-timeline-img -->
<div class="cd-timeline-content">
<div class="post-title">
<h2>First Title</h2>
</div>
<div class="post-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum.</p>
</div>
<a href="#0" class="cd-read-more">Read more</a>
<span class="cd-date">July 17 2017</span>
</div>
<!-- cd-timeline-content -->
</div>
<!-- cd-timeline-block -->
<div id="simpleModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2 id="modal-title"><span class="closeBtn">×</span></h2>
</div>
<div class="modal-body">
<div id="map"></div>
</div>
<div class="modal-footer">
<h4>Test Footer</h4>
</div>
</div>
</div>
<!-- END MODAL -->
答案 0 :(得分:0)
感谢大家的投入和线索。出于挫败感,我结束了使用jQuery而不是vanilla JS。我会说(我正确使用它吗?)它作为一个强化练习进入香草JS,但我现在只想要它的功能。
作为参考,这是我结束的代码:
$(document).ready(function(){
//set click function on read more button
$(".cd-timeline-block").on("click", function(){
//selects modal title and empties of content
$(".modal-title").empty();
// //select modal body and empties it
$(".modal-body").empty();
//set variable title as click selector
var title = $(".post-title", this);
//set variable body content as click selections body
var body = $(".post-body", this);
$(title).clone().appendTo(".modal-title");
$(body).clone().appendTo(".modal-body");
})
});
&#13;