点击按钮后页面刷新

时间:2021-01-17 14:09:24

标签: javascript page-refresh

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

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>

3 个答案:

答案 0 :(得分:3)

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

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

要么使用 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>

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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>