简体   繁体   English

jQuery 按键事件 function 不工作

[英]jQuery keypress event function not working

I am trying to add a keypress event into my dynamically created input element.我正在尝试将按键事件添加到我动态创建的输入元素中。

The keypress event doesn't work when I execute the code.当我执行代码时,按键事件不起作用。 Where have I gone wrong?我哪里出错了?

 var input = document.createElement("input"); input.className = "installments"; $(document).ready(function() { $('.installments').keypress(function() { if (+$('.installments').val() <= 0 || +$('.installments').val() > 12) alert("Installments should be within 1-12 months range"); }); }); document.querySelector('#testElement').appendChild(input);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="testElement"></div>

The problem is primarily that you can't get the value of an element set, which is what $('.installments') returns.问题主要是您无法获取元素集的值,这就是$('.installments')返回的值。 See https://api.jquery.com/class-selector .请参阅https://api.jquery.com/class-selector You'd have to refine the selector or take the first element by index, or use this as I've done here.您必须优化选择器或按索引获取第一个元素,或者像我在这里所做的那样使用this

Then, you're using the keypress event, which fires before a value has been set.然后,您正在使用keypress事件,该事件在设置值之前触发。 I've changed it to keyup .我已将其更改为keyup

I'd also suggest setting your input to type number for better input validation, though a select element with specific options values may actually be the best UX approach.我还建议将您的输入设置为类型number以便更好地验证输入,尽管具有特定选项值的 select 元素实际上可能是最好的 UX 方法。

Then, alerts are a terrible UX mechanism.然后,警报是一种糟糕的用户体验机制。 They require the user to take useless action, and they're not stylable.它们要求用户采取无用的操作,而且它们不可样式化。 Look to HTML validation or custom inline messaging instead.请改用 HTML 验证或自定义内联消息。

Finally, let and const are more modern ways to store values.最后, letconst是更现代的存储值的方法。 They have better safety checks and more intuitive scoping.他们有更好的安全检查和更直观的范围界定。

 let input = document.createElement("input"); input.type = 'number'; input.className = "installments"; $(function() { // shorthand for document.ready $('.installments').keyup(function() { const inputVal = parseInt($(this).val()); console.log(inputVal); if (inputVal <= 0 || inputVal > 12) console.log("Installments should be within 1-12 months range"); }); }); document.querySelector('#testElement').appendChild(input);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="testElement"></div>

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

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