1

我正在制作一个简单的 JavaScript 函数,您在表单中输入两个数字,然后该函数确定这两个数字的总和是否为质数。一切正常,但是当函数显示带有 document.getElementById("demo").innerHTML 和

它只在网页上停留一秒钟然后消失。我想这样做,以便消息一直存在,直到您再次单击该按钮。我已经搜索了这个网站和其他网站,但没有找到任何东西。

这是代码:

<!DOCTYPE html>
<html>
<head>
<link href="/prime.css" rel="stylesheet" type="text/css" />
<script>
function prime()
 {
  // get the values from the form
 var x= document.forms["frm1"]["x"].value; 
 var y= document.forms["frm1"]["y"].value;
  //test the values of the form
 if (x == "null"|| x=="" || isNaN(x)|| y=="null" || y==""|| isNaN(y)){
 alert("You must enter two numbers.");
 exit;
 }
  //change variables to number and add them together
  var number = (parseInt(x)+ parseInt(y));
   var a="";
 var prime = true;

  //check to make sure number is not less than one
 if (number <= 1){
 alert("Sorry " +number+ " is not a prime.");
 prime = false;
 exit;
 }
   //check if number is a prime
for (var dividby = 2; dividby <= number / 2; dividby++){
if(number % dividby == 0)
    prime = false;
break;

}
    //send congratulations
if(prime==true){

a="congratulations " + number + " is a prime!";
}
   //send condolences
else{
a="Sorry "+number+ " is not a prime.";
}
document.getElementById("demo").innerHTML=a;

}

</script>
</head>

<body id="elem">
<div class="div"></div>
<div> 
    <br>
<h1>PRIME NUMBERS</h1>
<p>Please enter two numbers to be added and see if the result is a prime.</p><br>
<form name="frm1" >
<input type="text" name="x"> 
+ <input type="text" name="y">
<button onclick="prime()">click me</button>
</form>
<br>
<p id="demo"></p>
</div>
</body>
</html>
4

3 回答 3

4

The problem is that your "click me" button is actually submitting the form, causing the page to reload (since your <form> doesn't have an action attribute, it submits to the same page). The <button> tag defaults to type="submit". To make it NOT a submit button, you need to change it like this:

<button onclick="prime()" type="button">click me</button>

于 2013-02-24T19:05:40.620 回答
1

I just tried the code, and what happens is simple: your form is posted when you click the button.

In the button onClick, write onClick=" return prime();" and add a

return false;

in your javascript function.

于 2013-02-24T19:06:32.217 回答
0

在您的表单标签中,只需添加 onsubmit="return false;" 像这样-

<form name="frm1" onsubmit="return false;" >

这将阻止您的表单被提交。

于 2013-02-24T19:43:16.390 回答