简体   繁体   English

为什么 keyup 有效但 keydown 无效

[英]Why keyup works but keydown does not work

I have an input type="number" where the min value is 1, the max is 10. I want to prevent inputting a value greater or less than max and min, so I use this script:我有一个输入类型=“数字”,其中最小值为 1,最大值为 10。我想防止输入大于或小于最大值和最小值的值,因此我使用此脚本:

 $('input[name=inputModal1]').keyup(function(){ if($(this).val()>10){ $(this).val(10); }else if($(this).val()<1){ $(this).val(1);} }); $('input[name=inputModal2]').keydown(function(){ if($(this).val()>10){ $(this).val(10); }else if($(this).val()<1){ $(this).val(1);} });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" name="inputModal1" min="1" max="10" value="1"> <input type="number" name="inputModal2" min="1" max="10" value="1">

In this kind the script works, but I want to use keydown , it prevents entering more or less than the maximum and minimum value, but keyup gives more or less typing if the user presses and holds the button.在这种情况下,脚本可以工作,但我想使用keydown ,它可以防止输入多于或少于最大值和最小值,但如果用户按住按钮, keyup会提供或多或少的输入。 What could be the reason that keydown is not working? keydown不起作用的原因可能是什么? I can remove the value, make it more than 10, etc.我可以删除该值,使其超过 10,等等。

Let me know if you need more information.如果您需要更多信息,请与我们联系。

The issue is to do with the order of events.问题与事件的顺序有关。 keydown fires on the element before the value has been set. keydown在设置值之前触发元素。 Therefore $(this).val() is '' when the event fires, which confuses your logic.因此,当事件触发时$(this).val()'' ,这会混淆你的逻辑。

To fix this issue, and improve the behaviour, use the input event instead.要解决此问题并改进行为,请改用input事件。 This works as you require, and also fires when the user adds content to the element in any way - pasting via the mouse for example.这可以根据您的需要工作,并且当用户以任何方式向元素添加内容时也会触发 - 例如通过鼠标粘贴。

In addition you can use Math.min() and Math.max() to make your logic more succinct.此外,您可以使用Math.min()Math.max()使您的逻辑更简洁。 Try this:尝试这个:

 $('input[name=inputModal]').on('input', function() { $(this).val((i, v) => Math.max(Math.min(this.value, 10), 0)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" name="inputModal" min="1" max="10">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM