为什么这会调用我的 Action 两次?对于背景,仅当用户单击表单上的其他位置时,使用 .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
在 input
后触发超过 1000 毫秒> 触发,因为 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>
如果您 Hook input
,则无需 Hook change
。
关于javascript - 为什么 JQuery $.post 提交两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557414/