首页 > 解决方案 > 使用 javascript 创建选项弹出窗口

问题描述

我正在尝试编写一些在网站登录页面上创建弹出窗口的代码。我需要的是一个带有一些文本的弹出窗口和两个带有两个不同选项的按钮。其中一个使弹出窗口消失并在站点中正常继续,另一个离开页面并重定向到其他地方。鉴于我现在对 javascript 不太了解,我有点迷失了两段代码,它们分别完成了我需要的一半事情。

我知道代码的每一部分都给出了我需要的结果,但我不知道如何以它们的工作方式加入它们。

这部分代码会打开一个弹出窗口,允许您选择留在页面还是离开

</script>
<a href="http://www.google.com">test this</a>
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
</script>

这种和平的代码有点怪诞,没有多大意义,但它会打开一个不错的弹出窗口,我想在其中获取上述选项,而不是现在显示的文本

<SCRIPT Language="JavaScript">
var q = "do you know how much is 2+2?";
var a = 4;
var c = "<h2>yyyyyeeeeeeeyyyyyyy</h2>";
var ic = "<h2>w*nker</h2>";
var response = prompt(q,"0");
if (response != a) 
{ alert("buuuuh"); }
else { alert("oh yes!!! oh yes!!!"); }
var o = (response == a) ? c : ic;
document.write("<BR/>");
document.write(o);
</SCRIPT>

所以,我需要一个弹出窗口,有两个按钮,离开页面,留在页面中......然后我将处理自定义和整个 shananigans

标签: javascripthtmlpopupwindowpopupmenu

解决方案


您可以尝试confirm()在 JS 中使用事件,您想要的背后的逻辑几乎是这样的:

var popup = confirm("Do you want to leave the page ?");

if (popup == true) {
  window.close(); //For an example, but you could change the URL of the website to another on, or do whatever you want here...
} else {
        return false; //or open another popup, etc, you choose what you need over the function...
  }

然后你只需要在你做的提示之后或在一个按钮或任何你想要的东西中调用它


推荐阅读