javascript - 具有相同脚本的多个模式
问题描述
我有以下代码处理页面上的模式打开和关闭。我希望能够在同一页面上加载第二个模式。它将具有相同的类“.custom-modal”,但 ID 不同。
使用我当前的代码,两个模态都打开,但只有第一个模态能够关闭。
var modal;
// Get the button that opens the modal
var btns = document.querySelectorAll(".customModalTrigger");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("custom-close")[0];
var body = document.body;
// When the user clicks the button, open the modal
[].forEach.call(btns, function(el) {
el.onclick = function() {
// Get the modal
modal = document.querySelector('#' + el.id + '.custom-modal');
modal.classList.add('-show');
body.classList.add('noscroll');
}
})
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.classList.remove('-show');
body.classList.remove('noscroll');
}
解决方案
你的问题是这样的:
var span = document.getElementsByClassName("custom-close")[0];
具体来说,[0]
. 您仅将事件侦听器应用于第一个匹配元素,而没有其他元素。相反,请尝试:
var span = document.getElementsByClassName("custom-close");
for (var i = 0; i < span.length; i++){
span[i].onclick = = function() {
modal.classList.remove('-show');
body.classList.remove('noscroll');
}
}
推荐阅读
- django - 无法过滤、排序和搜索嵌套端点 API 的数据
- c++11 - lambda 异步调度问题捕获的成员函数
- javascript - 单击标题时动态展开/折叠
- reactjs - ReactDOM.render 中传递的组件参数类型是什么?
- google-chrome - 为什么有时通过 HTTP 有时通过 HTTP/2 从 Chrome 向我的网站发送请求?
- reactjs - 将 props 传递给父组件
- security - WebLogic App 服务器(数据库池)上密码服务器的数据库架构密码
- reactjs - 在 ReactJS 中使用 AWS Cognito 和 AXIOS 刷新令牌的最佳实践/方法
- javascript - 需要一个需要相同文件的模块会导致 Node.js 出现问题吗?
- git - 如何在新位置创建新分支作为其他分支的延续