javascript - 如何检测快速的 .change() 事件?

标签 javascript jquery

我有以下内容:

$(document).ready(function () {
    var timer;    
    $('.coInput').on('change', function () {
        var itemID = $(this).attr('data-id');
        var rate = $(this).val();
        var $this = $(this);
        $this.prop('disabled', true);
        clearTimeout(timer);
        timer = setTimeout(function() {
            $.ajax({
                url: '/update_crackout/',
                type: 'POST',
                dataType: 'json',
                data: {
                    'object': itemID,
                    'rate': rate
                },
                success: function(data) {
                    $('#weight-'+itemID).html(data.weight);
                    $('#price-'+itemID).html(data.price);
                    $this.prop('disabled', false);
                }
            })
        }, 500)
    })
});

它似乎并不能始终如一地工作。它指向一个数字字段。当我使用向上/向下箭头更改值时,它第一次起作用,然后仅间歇性地起作用。是什么导致 .change() 错过我的一些更改?

我尝试删除除单个 console.log() 之外的所有内容,它做了同样的事情。

最佳答案

根据MDN :

The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each change to an element's value.

(emphasis mine)

因此,如果您需要在每次更改时触发该事件,请使用“input”事件。

这是一个代码笔来显示它的工作原理:https://codepen.io/Nisargshah02/pen/BJPYoY

$("input").on("input", function(){
  console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" name="" id="">

关于javascript - 如何检测快速的 .change() 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48258104/

相关文章:

javascript - jQuery 中的 for-each 循环等效于什么?

javascript - 如何使用 Ramda.js 合并 2 个组合

javascript - 单击按钮时设置元素的高度

jquery - 在页面 : Map invisible although present in HTML 中嵌入谷歌地图

jquery - InsertionMode.Replace 如何在 Ajax.BeginForm 上工作

javascript - 如何向其他用户显示 "User is typing..."?

javascript - 如何使用ko.observableArray?

javascript - 为什么 console.log() 被调用两次而不是一次?

javascript - 最好使用哪种方法 - document.getElementById 或 document.forms[]?

javascript - hasClass() 总是返回 false (jquery) 即使在切换它时也是如此