【问题标题】:event.preventDefault() works in one case but not otherevent.preventDefault() 在一种情况下有效,但在其他情况下无效
【发布时间】:2018-12-18 14:45:07
【问题描述】:

我的页面上有两个表单,一个用于提交评论,另一个用于投票。这两个函数仅相隔几十行,但只有 #comment-form 的一个实际上阻止了默认值。 #poll-form 提交按钮刷新页面,这不是我想要的。

$("#comment-form").submit(function(event){
    event.preventDefault();
    addComment();
});

//ajax stuff for adding the comment, addComment() etc.

$("#poll-form").submit(function(event){
    event.preventDefault();
    castVote();
});

HTML 看起来像:

<div class="add-comment">
  <form id="comment-form">
    <textarea id="comment-content" name="comment" placeholder="Leave a comment"></textarea>
    <br>
    <button type="submit">Submit</button>
  </form>
</div>

<div class="poll">
  <h1 class="title">Poll</h1>
  <h3>Poll Question</h3>
    <form id="poll-form">
      <input type="radio" name="vote" value="0">
      Choice 1
      <br>
      <input type="radio" name="vote" value="1">
      Choice 2
      <br>
      <input type="radio" name="vote" value="2"> 
      Choice 3
      <br>
      <input type="radio" name="vote" value="3">
      Choice 4
      <br>
      <button type="submit">Submit</button>
    </form>
</div>

我看不出区别,也看不出为什么 #poll-form 提交不会阻止默认设置。

【问题讨论】:

  • 代码没有问题,可能是你的castVote();函数正在重新加载。检查功能
  • 我复制了你的代码并且 .preventDefault() 在这两种情况下都对我有用。也许 reload 来自castVote();
  • 在这个小提琴中尝试你自己的代码:jsfiddle.net/syamsoul/mwL78sah .... 你的代码没有任何问题...
  • 确保在添加事件侦听器之前,您的代码 console.assert($('[id="poll-form"]') === 1) 中没有重复的 id。
  • 如果您的表单是动态的,请使用此代码$(document).on("submit", "#poll-form", 'function(event){ event.preventDefault(); castVote(); });

标签: javascript jquery node.js express


【解决方案1】:

您也可以尝试停止表单提交,

$("#poll-form").submit(function(e){
  e.preventDefault();
  alert('it works!');
  return  false;
});

【讨论】:

  • 为什么要有所作为? preventDefault() 没有理由不工作。我想不出return false 会起作用而preventDefault() 不会起作用的任何情况。三个人已经在 cmets 中表示,他们无法重现该问题。
猜你喜欢
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 2019-12-27
相关资源
最近更新 更多