如何检测快速.change()事件?(How to detect rapid .change() events?)

编程入门 行业动态 更新时间:2024-10-04 15:26:36
如何检测快速.change()事件?(How to detect rapid .change() events?)

我有以下几点:

$(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()和它做了同样的事情。

I have the following:

$(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) }) });

It doesn't seem to work consistently. It is pointed at a number field. When I use the up/down arrows to change the value, it works the first time, then only intermittently after that. What causes .change() to miss some of my changes?

I tried removing everything except for a single console.log() and it did the same thing.

最满意答案

根据MDN :

当用户提交对元素值的更改时,会为<input> , <select>和<textarea>元素触发更改事件。 与输入事件不同,更改事件不一定会针对元素值的每次更改触发

(强调我的)

因此,如果您需要在每次更改时解雇事件,请使用“输入”事件。

这是一个codepen来显示它的工作: 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=""> 
  
 

According to 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)

So, if you need the event to be fired with every change, use "input" event.

Here's a codepen to show it working: 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=""> 
  
 

更多推荐

本文发布于:2023-08-04 21:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1422273.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   事件   change   events   detect

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!