为什么这两次调用我的操作?对于背景,仅当用户单击表单上的其他位置时,才可以使用.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;
}
答案 0 :(得分:4)
可能是因为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>
如果钩住input
,则无需钩住change
。