单击弹出窗口中的“取消”后,我的按钮不会取消

时间:2021-01-06 20:50:32

标签: javascript

我有一个用作链接的按钮。 onclick 是如下所示的 myAlert() 函数。该函数会创建一个弹出窗口,询问您是否要继续。即使您点击“取消”,它仍会转到下一页。我该怎么办?

<!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>

2 个答案:

答案 0 :(得分:0)

使用$wgDefaultSkin = "vector"; wfLoadSkin( 'MinervaNeue' ); $wgMFAutodetectMobileView = true; wfLoadExtension( 'MobileFrontend' ); 方法取消属于下一页的默认动作。

preventDefault()
function myAlert(e) {
  
  if (confirm('Are you sure you want to sign up?')) {

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

答案 1 :(得分:0)

您将按钮放置在链接本身内。因此,在关闭对话框后,浏览器会处理链接的 onclick 事件,从而浏览到链接目标。

您可以完全删除链接元素并使用按钮处理所有内容:

<!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>