簡體   English   中英

確認取消按鈕不適用於這個簡單的代碼

[英]confirm cancel button not working for this simple code

確認/取消按鈕不起作用,我不知道是什么問題。

即使單擊確認框取消后,它仍然會將我引導到另一個頁面。

<html>
    <head>
        <title>password</title>
    </head>
    <body>
        <script type="text/javascript">
            function f() {
                if (myform.password.value == "") {
                    window.alert("you need to enter your password");
                } else {
                    window.confirm("are you sure u want to proceed");
                    window.location =' https://www.facebook.com/';
                }
            }
        </script>
        <center>
            <h1>confirm password page</h1>
            <form id="myform">
                Enter the Password
                <input type="password" id="password" value="">
                <input type="button" id="continue" value ="continue" onclick="f()">
            </center>
        </form>
    </body>
</html>

你可以做

if(window.confirm("are you sure u want to proceed")) {
      // Proceed to next page
}

confirm() 方法顯示一個對話框,其中包含一條消息、一個確定按鈕和一個取消按鈕。

如果用戶單擊“確定”,confirm() 方法返回 true,否則返回 false。

Window.confirm()返回一個boolean

  • 如果確定單擊則為true
  • 如果單擊取消,則為false

所以你必須像 if-else 塊一樣處理。

if(window.confirm("are you sure u want to proceed")){
// your redirection logic here.
}

我改了

 function f(){ if(myform.password.value==""){ window.alert("you need to enter your password"); } else{ if (window.confirm("are you sure u want to proceed")) { window.location =' https://www.facebook.com/'; } } }
 <center> <h1>confirm password page </h1> <form id="myform"> Enter the Password<input type="password" id="password" value=""> <input type="button" id="continue" value ="continue" onclick="f()"> </form> </center>

表單的默認行為導致指向另一個頁面。 為了防止這種行為,您應該在表單上使用preventDefault() 喜歡:

event.preventDefault();

這是一個示例:

https://codepen.io/navab/pen/YzemrWB

只需復制粘貼我的代碼,當您按取消時它會返回您

<html>
    <head>
        <title>password</title>
    </head>
    <body>
        <script type="text/javascript">
            function f() {
                if (myform.password.value == "") {
                    window.alert("you need to enter your password");
                } else {
                    if(window.confirm("are you sure u want to proceed")==true){
                    window.location =' https://www.facebook.com/';}
                    else{
                      window.location.reload();
                    }
                }
            }
        </script>
        <center>
            <h1>confirm password page</h1>
            <form id="myform">
                Enter the Password
                <input type="password" id="password" value="">
                <input type="button" id="continue" value ="continue" onclick="f()">
            </form>
        </center>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM