JavaScript表单的异常行为

时间:2019-03-04 08:47:48

标签: javascript html

在将值输入为22后单击“单击我”按钮时,网页上看不到任何更改。我该如何解决?

function fun() {
  n = document.getElementById("number").value;
  headingTag = document.getElementById("h2");
  headingTag.innerText = n;
}
<form>
  <input type="text" id="number">
  <button onclick="fun()">Click Me!</button>
</form>
<h2 id="h2"></h2>

2 个答案:

答案 0 :(得分:0)

使用preventDefault()通过按钮停止表单提交行为。 Refer

function fun(e) {
  e.preventDefault();
  n = document.getElementById("number").value;
  headingTag = document.getElementById("h2");
  headingTag.innerText = n;
}
<body>
  <form>
    <input type="text" id="number">
    <button onclick="fun(event)">Click Me!</button>
  </form>
  <h2 id="h2"></h2>
</body>

答案 1 :(得分:0)

这是因为按钮的默认类型 submit 。因此,在单击时,将提交表单。您可以使用Event.preventDefault()来阻止该事件,也可以在按钮中指定type="button"

<body>
   <form>
       <input type="text" id="number">
       <button onclick="fun(event)">Click Me!</button>
   </form> 
   <h2 id="h2"></h2>
   <script>
       function fun(e){
         n = document.getElementById("number").value;
         headingTag = document.getElementById("h2");
         headingTag.innerText = n;
         e.preventDefault();
       }
   </script>
</body>

通过更改类型:

<body>
   <form>
       <input type="text" id="number">
       <button type="button" onclick="fun()">Click Me!</button>
   </form> 
   <h2 id="h2"></h2>
   <script>
       function fun(){
         n = document.getElementById("number").value;
         headingTag = document.getElementById("h2");
         headingTag.innerText = n;
       }
   </script>
</body>