javascript - 为什么 JQuery $.post 提交两次?
问题描述
为什么这会两次调用我的操作?对于背景,使用 .change 仅在用户单击表单上的其他位置时才有效。当浏览器关闭时,.change 也不会触发。因此,计时器与数据脏属性检查相结合。提前致谢。
var timeoutId;
$(function() {
var formElements = $('#myformid').find('input, select, textarea').add('[form=myformid]').not(':disabled').each(function() {
$(this).attr('data-dirty', false).on('input propertychange change', function() {
var changedText = $(this).val();
var commentID = $(this).attr('id');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
// Runs 1 second (1000 ms) after the last change
// Saving to DB Here
$.post('@Url.Action("UpdateComment", "CommentJournal")', {
"ChangedText": changedText,
"commentID": commentID
});
$(this).attr('data-dirty', true);
}, 1000);
});
});
});
//Controller
[HttpPost]
[AllowAnonymous]
public ActionResult UpdateComment(string changedText, string commentID) {
return null;
}
解决方案
可能是因为input
和change
事件都被触发,change
触发后触发超过 1000 毫秒input
,因为change
只有在焦点离开控件时才会触发。例子:
var timerId = 0;
$("#field1").on("input change", function(event) {
var type = event.type;
clearTimeout(timerId);
timerId = setTimeout(function() {
console.log("timeout fired for '" + type + "'");
}, 1000);
});
<p>Type something in the first field, wait at least a second, then tab out of the field:</p>
<div>
<label>
First field:
<input type="text" id="field1">
</label>
</div>
<div>
<label>
second field:
<input type="text" id="field2">
</label>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果你钩input
了,就没有必要钩了change
。
推荐阅读
- scala - How to correctly verify scheduled invocations in ZIO Test
- python - 如何使用 imsave 保存带有颜色条的图像?
- laravel - 借助关系获取 Laravel 中父类别和子类别中的所有产品
- selenium - selenium pagefactory中的elementlocatorFactory有什么用,有一些真实的语法
- swift - 为子视图控制器使用自动布局
- excel - Selenium VBA Excel - 单击 iframe 中的链接时出现问题
- c# - Newtonsoft.Json C# :: 格式化 JsonConvert.SerializeObject
- javascript - DOM 操作在模板文字中不起作用
- javascript - 如何创建重复的 webpack 块文件,一个有一个没有哈希?
- reactjs - React Router - 嵌套链接重定向到自定义 404 页面