簡體   English   中英

為什么JQuery $ .post提交兩次?

[英]Why does JQuery $.post submit twice?

為什么這兩次調用我的動作? 對於背景,僅當用戶單擊表單上的其他位置時,才可以使用.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;
}

大概是因為這兩個inputchange事件被解雇,與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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM