为什么是event.preventDefault();不在这里工作?

时间:2016-05-02 10:45:02

标签: javascript html

浏览器网址不应该被更改,但无论如何都是如此。应该通过cityNameSubmit按钮的事件侦听器中的event.preventDefault()来阻止这种情况。

<!DOCTYPE html>
<html>
  <head>
    <script>
    function bindButton() {
      document.getElementById('cityNameSubmit').addEventListener('click', function (event) {
        event.preventDefault();
      })
    }
    </script>
  </head>
  <body>
    <form>
      <fieldset>
        <legend>Choose a City</legend>
        <input type="text" name="cityName" id="cityName">
        <input type="submit" id="cityNameSubmit">
      </fieldset>
    </form>
  </body>
</html>

3 个答案:

答案 0 :(得分:0)

您创建了一个函数,但忘了调用此函数。试试这个:

<script>
function bindButton() {
  document.getElementById('cityNameSubmit').addEventListener('click', function (event) {
    event.preventDefault();
  })
}
window.onload = function() {
bindButton();
}
</script>

答案 1 :(得分:0)

你需要在某个地方调用函数bindButton()或者只是删除这个函数定义并只留下

document.getElementById('cityNameSubmit').addEventListener('click',function(event){
    event.preventDefault();
})

答案 2 :(得分:0)

事实上,在您的实际代码中,您只是声明函数bindButton(),您必须使用body onload来调用它以附加事件,例如在<body onload="bindButton()">事件中像这样:

<!DOCTYPE html>
<html>

<head>
  <script>
    function bindButton() {
      document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
        event.preventDefault();
        console.log("form submission prevented !");
      })
    }
  </script>
</head>

<body onload="bindButton()">
  <form>
    <fieldset>
      <legend>Choose a City</legend>
      <input type="text" name="cityName" id="cityName">
      <input type="submit" id="cityNameSubmit">
    </fieldset>
  </form>
</body>

</html>

甚至更好地使用立即调用的函数表达式(IIFE),如下所示:

(function() {
  document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
    event.preventDefault();
    console.log("form submission prevented !");
  })
})();

<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <form>
    <fieldset>
      <legend>Choose a City</legend>
      <input type="text" name="cityName" id="cityName">
      <input type="submit" id="cityNameSubmit">
    </fieldset>
  </form>

  <script>
    (function() {
      document.getElementById('cityNameSubmit').addEventListener('click', function(event) {
        event.preventDefault();
        console.log("form submission prevented !");
      })
    })();
  </script>
</body>

</html>

注意:

确保将脚本放在body标记的末尾,以确保解析HTML。