【发布时间】: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