点击按钮后页面刷新

Page refreshes after I hit the button

这是一个简单的元音计数页面。当我插入一个带有元音的单词时,结果会显示一秒钟,然后页面会刷新。当没有元音时,输出不符合预期,然后页面再次刷新。谁能帮帮我吗?

function findVow(event) {
  event.preventDefault();
  var input, result;
  // Get value of the input
  input = document.getElementById('text').value;
  var regex = /[aeiou]/gi;
  //unify the case and get the length
  var count = input.match(regex).length;

  if (count > 0) {
    result = "Vowels found : " + count;
  } else {
    result = "No vowels found";
  }
  //print the number of vowels if any
  document.getElementById("demo").innerHTML = result;
};
<!DOCTYPE html>
<html>

<head>
  <title>challenge1</title>
</head>

<body>
  <form>
    <input id="text" placeholder="Enter a word" type="text" />
    <br><br>
    <button onclick="findVow()">Count vowels</button>
    <br>
    <p id="demo"></p>
  </form>
  <script type="text/javascript" src="script.js"></script>
</body>

</html>

type='button'添加到表单中的按钮

<button onclick="findVow()" type='button'>Count vowels</button>

您正在使用默认按钮提交表单。

您想要的事件没有按预期传递 - 传递的是按钮。

要么使用 type=button 要么更好:像现在一样使用 event.preventDefault,但在提交事件上

document.getElementById("myForm").addEventListener("submit", function(event) {
  event.preventDefault();
  var input, result;
  // Get value of the input
  input = document.getElementById('text').value;
  var regex = /[aeiou]/gi;
  //unify the case and get the length
  var count = input.match(regex).length;

  if (count > 0) {
    result = "Vowels found : " + count;
  } else {
    result = "No vowels found";
  }
  //print the number of vowels if any
  document.getElementById("demo").innerHTML = result;
});
<form id="myForm">
  <input id="text" placeholder="Enter a word" type="text" />
  <br><br>
  <button>Count vowels</button>
  <br>
</form>
<p id="demo"></p>

type="button"添加到按钮,如果你想捕获按钮事件,你可以这样做:

$('btnClick').on('click',function(event){
  event.preventDefault();
  var input, result;
  // Get value of the input
  input = document.getElementById('text').value;
  var regex = /[aeiou]/gi;
  //unify the case and get the length
  var count = input.match(regex).length;

  if (count > 0) {
    result = "Vowels found : " + count;
  } else {
    result = "No vowels found";
  }
  //print the number of vowels if any
  document.getElementById("demo").innerHTML = result;
});
<!DOCTYPE html>
<html>

<head>
  <title>challenge1</title>
</head>

<body>
  <form>
    <input id="text" placeholder="Enter a word" type="text" />
    <br><br>
    <button class="btnClick" type="button" >Count vowels</button>
    <br>
    <p id="demo"></p>
  </form>
  <script type="text/javascript" src="script.js"></script>
</body>

</html>