javascript - .preventDefault() 不再正常运行
问题描述
我必须错过一些简单的东西。该脚本按预期运行,直到我添加了一个新元素来使用导航栏中的按钮切换输入框。现在表单将在提交时重定向。
预期的行为是,当输入提交时,它会在评论框下方显示为评论。
目前我的 .preventDefault(); 当我被重定向时,不再处理点击。我花了太多时间试图找出问题所在,并且需要对我更改或实施不正确的内容有所了解。
$(function () {
//Toggle compose input box
$(".compose").click(function () {
event.preventDefault();
$(".new").slideToggle("slow");
textarea.focus()
})
//compose input to comment
$('.Form').on('submit', function (event) {
event.preventDefault();
// 1. Grab the content of the form
let formData = $('.Form').serialize();
let entry = $('.textarea input').val();
console.log(entry)
if (entry === null || entry === '') {
alert('text too short!')
} if (entry.length > 140) {
alert('text too long!')
} else {
// 2. Submit using ajax
$.ajax('/comments', {
method: 'POST',
data: formData,
}).then(function (success) {
console.log('succesful')
// 4. Make sure the new comments shows
return $.ajax('/comments');
}).then(renderComments());
}
});
});
html:
<main class="container">
<section class="new">
<form action='/comments' Method='POST' id="Form">
<h2>Compose Comment</h2>
<textarea id="textarea" name="text" onfocus='this.select()' placeholder="What are you humming about?"></textarea>
<input class="submit" type="submit" value="Submit">
<span class="counter">140</span>
</form>
</section>
解决方案
您的表单具有 id="Form",但您正在使用 jQuery 选择类。
即你需要:
//compose input to comment
$('#Form').on('submit', function(event) {
event.preventDefault();
}
小心,序列化逻辑也在使用类,更新你的引用。
推荐阅读
- c# - 当我们通过 id 获取记录时使用 Linq 查询如何将该值分配给另一列?
- php - 如何在不硬编码我的 mysqli 查询的情况下更新我的表单
- javascript - classList.add() 不会在单击事件中立即激活
- git - GIT 存储库迁移冲突(重命名/重命名)
- javascript - free-jqgrid 方法和参数列表?
- python - 为什么appium在新浪新闻文本框中输入中文会乱码
- python - 为什么我的 python 服务器请求在尝试从 redis 存储(在 nginx openresty 中)获取子请求时仍处于不确定状态?
- javascript - 在 iframe 中打开 iframe 网站中的链接
- reactjs - 如何在 Next.js 中绕过 _app.js
- estimote - 未找到 Android 信标:Google 信标仪表板