Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - My button will not cancel after clicking "cancel" in my popup

I have a button that acts as a link. The onclick is the myAlert() function shown below. The function creates a popup asking if you want to continue. It still goes to the next page even if you hit "cancel". What should I do?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body bgcolor="grey" align="center">
<a href="333.html"><button onclick="myAlert()">Sign up</button></a><a href="22.html"><button >Log in</button></a> 

<script>
    function myAlert(){
        if (confirm('Are you sure you want to sign up?')) {

  console.log('Thank you.');
} else {


}
    }
    </script>       
            
  
    </body>
</html>
question from:https://stackoverflow.com/questions/65603197/my-button-will-not-cancel-after-clicking-cancel-in-my-popup

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You placed the button inside the link itself. Therefore after closing the dialog, the browser processes the onclick event of the link which results in browsing to the to the link target.

You can remove the link elements completely and handle everything using the buttons:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body bgcolor="grey" align="center">
<button onclick="myAlert('333.html')">Sign up</button><button onclick="window.location.href='22.html'">Log in</button> 

<script>
    function myAlert(redirect){
        if (confirm('Are you sure you want to sign up?')) {
           window.location.href=redirect
  console.log('Thank you.');
} else {


}
    }
    </script>       
            
  
    </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...