[英]How to close template modals in handlebars?
我创建了一个应用程序来接收来自新闻 API 的文章。 每篇文章都显示在一张卡片中,卡片上有一个“打开模式”按钮。 此按钮打开一个模式,其中包含与每篇文章相关的唯一信息。
但是,一旦打开模式,我就无法关闭它。 我怀疑这是因为模态卡在这个 state: modals.forEach((modal, index) => {modal.classList.toggle('open', index === openIndex);
这是我当前的代码:
{{!-- #each article --}}
<div class="row">
{{#each articles}}
<div class="col-12-sm col-6-md col-3-lg">
<div class="card m-2">
<div class="card-body">
<h5 class="card-title">{{title}}</h5>
<p class="card-text">{{description}}</p>
</div>
<img class="card-image" src="{{urlToImage}}" alt="Card image cap">
<button data-open-modal="{{@index}}">Open Modal</button>
</div>
</div>
{{/each}}
</div>
</div>
{{#each articles}}
<!-- The Modal -->
<div class="modal closed" id="Modal_{{@index}}">
<!-- Modal content -->
<div class="modal-content">
<span id="spm" class="close" >×</span>
<h2>{{title}}</h2>
<img src="{{urlToImage}}" alt="">
<p>{{content}}</p>
</div>
</div>
{{/each}}
<script>
//Store all modals and modal buttons in variables
const openModalButtons = document.querySelectorAll('[data-open-modal]');
const modals = document.querySelectorAll('.modal');
//Loop through all modal buttons and assign handler to each
openModalButtons.forEach(openModalButton => {
openModalButton.addEventListener('click', (event) => {
//Get index value from number clicked
const openIndex = Number(event.target.dataset.openModal); //Access dataset attribute to read and write
//Loop over each modal.
//Set modal class to open if index is equal to wanted index
modals.forEach((modal, index) => {
modal.classList.toggle('open', index === openIndex);
modal.classList.toggle('closed', index !== openIndex);
});
});
});
</script>
这是我尝试添加到脚本中的内容:(它没有给出错误但什么也没做)
const span = document.querySelectorAll('.close');
let spanArr = Array.prototype.slice.call(span);
spanArr.forEach(spanArr => {
spanArr.addEventListener('click', (event) => {
const closeIndex = Number(event.target.dataset.closeModal);
spanArr[closeIndex].forEach(span => {
span.onclick = function() {
modal.style.display = "none";
}
});
});
});
我还尝试将事件侦听器添加到跨度,但我无法使其工作。 我是初学者,这是我第一次使用车把,所以感谢您的任何见解!
这里有一些问题可能是由于我在https://stackoverflow.com/a/73738690/3397771中没有解释。
一、 const openIndex = Number(event.target.dataset.openModal);
的原因有效是因为在每个“打开”按钮上定义了一个名为data-open-modal
的数据属性。 正是我们使用dataset.openModal
引用的数据属性,我们将返回的值是属性中等号右侧的值,即{{@index}}
部分。
但是,对于我们这里的目的,数据属性方法可能过于复杂。 或者,我们可以使用在forEach
循环中获得的index
来迭代地添加我们的点击事件监听器。
接下来,在我们的点击处理程序中不需要spanArr[closeIndex].forEach(...
循环spanArr
- 尽管它的名字 - 不是 arr(ay);它是单个span
元素。
更新后的代码变为:
const span = document.querySelectorAll('.close');
span.forEach((spanArr, index) => {
spanArr.addEventListener('click', () => {
modals[index].style.display = "none";
});
});
注意:我保留了我找到的变量的名称,但它们可以而且应该改进。 例如, span
没有传达这些元素的目的是什么,或者就此而言,它是一个集合。 closeButtons
会是一个更好的名字。 事实上,表现得像按钮的元素应该使用<button>
元素,而不是<span>
,以便在语义上正确且可访问。
我创造了一个新的小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.