javascript implements determine and cancel prompt box effects

  • 2020-07-21 06:57:40
  • OfStack

In many web pages, click a button or other object will pop up a prompt box. If you click OK, you will continue to execute the established program; if you click Cancel, you will cancel the execution. The code example is as follows:


<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title> Confirm and cancel the prompt box </title>
<style type="text/css">
div
{
 width:150px;
 margin:0px auto;
}
a
{
 font-size:12px;
 color:blue;
}
</style>
<script type="text/javascript">
window.onload=function(){
 var mylink=document.getElementById("mytest");
 mylink.onclick=function(){
  if(confirm(" Are you sure about the visit "))
  {
    return true;
  }
  else
  {
    return false;
  }
 }
}
</script>
</head>
<body>
 <div><a href="/" id="mytest"> Click the jump </a></div>
</body>
</html>

In the above code, a prompt box will pop up when you click the link. If you click OK, you will visit the home page of ant tribe. Otherwise, you will not visit it. At the heart of this is the use of confirm(), where the parameter value is the text content of the prompt box. Here is a brief introduction to the principle of the above code:

1. When the link is clicked, the onclick event handler bound to the a element is called.

2. In the event handler, since confirm() returns true when the OK button is clicked and false when the cancel button is clicked, the if statement selects whether to execute if or else based on the return value of confirm().

This is the end of this article, I hope you enjoy it.


Related articles: