我想在 javascipt 中制作一个定制的确认框,就像内置的确认框一样。除非用户至少选择一件事,否则内置确认框不允许代码继续运行。下面是我的代码: *****HTML 开头*****
<div class = "popUp confirm" style="z-index:40000;" id="confirmBlock">
<div id = "confirmLabel" >Confirm Message</div>
<div style ="border:0px solid red;height:44.56px;">
<input id="Confirm" type="button" value="Confirm" onclick = "confirmAction(1)" />
<input id = "CancelConfirm" type="button" value="Cancel" onclick = "confirmAction(0)" />
</div>
</div>
*****HTML 结尾*****
*****Javascript 启动*****
var confirmresult = "-1";
function confirmationLoop()
{
alert("If this alert is preesnt it works, seems like the built in alert provides some sort of pause for other parts of code to continue to work");
if(confirmresult == "-1")
confirmationLoop();
return;
}
function confirmAction(val)
{
confirmresult = val;
}
function checkuuu()
{
confirmresult = "1";
}
function confirmMessage(message)
{
document.getElementById("confirmLabel").innerHTML= message;
//var check = setTimeout(function(){confirmAction(1)},5000);
confirmationLoop();
/*
while(1) //using while almost does not allow any other part to run at all hence tried recursion
{
if(confirmresult != "-1")
break;
}
*/
document.getElementById("confirmLabel").innerHTML= "Confirm Message";
var returnVal = confirmresult;
confirmresult = -1;
return returnVal;
}
*****Javascript 结束*****
*****示例代码开始< em>***** 所以这就是我所期望的:
function example
{
var check = confirmMessage(message);
//the next part of code should not execute untill i press confirm or cancel, using settimeout or settimeinterval is asynchronous and the code flow continues. i want the effect something like alert and confirm built in boxes
}
*****示例代码结束< em>*****
我使用了循环,但它使线程完全被占用,并且不给我机会按下任何按钮,这是非常明显的 然而,递归使您可以自由地执行其他事件。即使按确认按钮后,confirmResult 的值将变为 1,我还是通过警报检查了该问题。递归循环,即确认循环似乎没有将其读取为 1。它仍然继续为 -1。如果我在确认循环中放置警报,则值将被读取为 1。任何人都可以帮助我实现我开始的目标吗??? P.s.=> 抱歉问了这么大的问题!!!
最佳答案
您不能使用任何类型的循环 - 因为您发现它只会导致浏览器锁定。
您需要做的是模拟一个“模态”对话框。
这通常是通过让对话框出现在另一个“覆盖”元素之上来完成的,该元素重要的是覆盖所有其他元素,并阻止任何用户与它们交互。
实现一个返回值的 confirm
函数也相当困难 - window.confirm
方法只能做到这一点,因为它是同步的 - 它会阻止所有其他方法对话框显示时的JS处理。
最简单的方法是提供一个回调函数,一旦用户选择了所需的值,该函数就会被调用。
关于javascript - 在 javascript 中制作自定义确认框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904635/