<p>标签出现并消失?

时间:2018-07-25 20:12:16

标签: javascript html

我有一个非常简单的程序,该程序使用JS将结果输出到<p>标记中。每当我运行结果时,<p>标记就会出现并迅速消失。

代码:

<!DOCTYPE html>
<html>
  <head>
   <meta charset="utf-8">
   <title>A2Q4</title>
   <link rel="stylesheet" href="style.css">
  </head>
 <body>
   <script>
    function NumberStats(number) {
      if(number.indexOf('soen287')>=0||number.indexOf('comp249')>=0||number.indexOf('assignment2')>=0) {
      number = number.replace(/soen287/gi,"SOEN287");
      number = number.replace(/comp249/gi,"COMP249");
      number =number.replace(/assignment2/gi,"ASSIGNMENT2");
      document.getElementById("p1").innerHTML ="&gt;&gt; "+number;
    } else{
      number=number.toUpperCase();
      document.getElementById("p1").innerHTML ="&gt;&gt; "+number;
    }
  }
   </script>
   <center>
   <br>
   <form name="myForm">
     <h1>Text detector<br/>A program created by Mohanad Arafe</h1>
     <input type="text" name="amount" placeholder="Enter your sentence"/>
     <button onclick="NumberStats(amount.value)">Try it</button>
     <p id="p1"></p>
   </form>
 </body>
</html>

2 个答案:

答案 0 :(得分:3)

这是因为该按钮被解释为提交按钮,所以它提交了表单并刷新了页面。您需要使用event.preventDefault()阻止表单的默认操作。

<!DOCTYPE html>
<html>
  <head>
   <meta charset="utf-8">
   <title>A2Q4</title>
   <link rel="stylesheet" href="style.css">
  </head>
 <body>
   <script>
    function NumberStats(number, e) {
     e.preventDefault(); if(number.indexOf('soen287')>=0||number.indexOf('comp249')>=0||number.indexOf('assignment2')>=0) {
      number = number.replace(/soen287/gi,"SOEN287");
      number = number.replace(/comp249/gi,"COMP249");
      number =number.replace(/assignment2/gi,"ASSIGNMENT2");
      document.getElementById("p1").innerHTML ="&gt;&gt; "+number;
    } else{
      number=number.toUpperCase();
      document.getElementById("p1").innerHTML ="&gt;&gt; "+number;
    }
  }
   </script>
   <center>
   <br>
   <form name="myForm">
     <h1>Text detector<br/>A program created by Mohanad Arafe</h1>
     <input type="text" name="amount" placeholder="Enter your sentence"/>
     <button onclick="NumberStats(amount.value, event)">Try it</button>
     <p id="p1"></p>
   </form>
 </body>
</html>

您还可以将button更改为<input type="button"><button type="button">(如Xufox在评论中建议的那样),以免浏览器将其误认为是“提交”按钮({{ 1}})。

<button type="submit">

答案 1 :(得分:0)

表单内按钮的默认行为是:

Some

浏览器会隐式地使它成为表单内的按钮,即使您编写的按钮没有以下类型:

flatMap

由于通过表单发送了新的HTTP请求,因此提交将触发页面刷新。我们可以通过以下方式轻松解决此问题:

  1. <button type="submit"></button>
  2. <button></button>

<input type="button"/>
<<button type="button"></button>