error with the modal pop up window closing up with onclick event javascript

huangapple go评论63阅读模式
英文:

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(&quot;myModal&quot;);

// Get the button that opens the modal
const btn = document.getElementById(&quot;myBtn&quot;);

// Get the &lt;span&gt; element that closes the modal
const close = document.getElementsByClassName(&quot;closeBtn&quot;);

// When the user clicks the button, open the modal
btn.onclick = function () {
  modal.style.display = &quot;block&quot;;
};

// When the user clicks on &lt;span&gt; (x), close the modal
close.onclick = function () {
  modal.style.display = &quot;none&quot;;
};

// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
  if (event.target == this.modal) {
    modal.style.display = &quot;none&quot;;
  }
};

<!-- 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(&quot;closeBtn&quot;)[0]; or set an id to the button instead

huangapple
  • 本文由 发表于 2023年4月19日 23:48:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定