英文:
error with the modal pop up window closing up with onclick event javascript
问题
尝试处理弹出窗口关闭的问题。但是我遇到了一个错误。问题是否与 "this" 关键字有关?
https://codesandbox.io/s/tours-test-slick-v1uw96?file=/index.js:626-1309
// 获取模态框
const modal = document.getElementById("myModal");
// 获取打开模态框的按钮
const btn = document.getElementById("myBtn");
// 获取关闭模态框的 <span> 元素
const close = document.getElementsByClassName("closeBtn");
// 当用户点击按钮时,打开模态框
btn.onclick = function () {
modal.style.display = "block";
};
// 当用户点击 <span>(x)时,关闭模态框
close.onclick = function () {
modal.style.display = "none";
};
// 当用户点击模态框外部的任何地方时,关闭模态框
window.onclick = function (event) {
if (event.target == this.modal) {
modal.style.display = "none";
}
};
请注意,上述代码中的 "this.modal" 可能是一个错误,您可能需要更正为 "modal"。
英文:
Trying to handle the popup window closing up. But I'm having an error. Is the issue reffered to the rhis keyword ?
https://codesandbox.io/s/tours-test-slick-v1uw96?file=/index.js:626-1309
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// Get the modal
const modal = document.getElementById("myModal");
// Get the button that opens the modal
const btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
const close = document.getElementsByClassName("closeBtn");
// When the user clicks the button, open the modal
btn.onclick = function () {
modal.style.display = "block";
};
// When the user clicks on <span> (x), close the modal
close.onclick = function () {
modal.style.display = "none";
};
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == this.modal) {
modal.style.display = "none";
}
};
<!-- end snippet -->
答案1
得分: 0
你正在尝试通过类名获取关闭按钮,这会返回一个包含所有元素的数组,因此,您需要对按钮进行具体指定。
您可以使用 const close = document.getElementsByClassName("closeBtn")[0];
或者给按钮设置一个id。
英文:
You are trying to get the close button by classname, this returns an array with all the elements so, you need to be especific with the button.
You can use const close = document.getElementsByClassName("closeBtn")[0];
or set an id to the button instead
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论