简体   繁体   English

onkeydown不工作,onblur工作

[英]onkeydown not working, onblur working

When I create a text box (input5) dynamically the next function works 当我动态创建文本框(input5)时,下一个功能有效

input5.onblur = function() {validate_quantity(this)}

but the next one, doesnt work 但是下一个不起作用

input5.onkeydown = function() {validateNumbers(event)}

When I load the page, I have a first text box in html, with 加载页面时,我在html中有第一个文本框,其中包含

onblur="validate_quantity" onkeydown="validateNumbers(event)

and BOTH work nice in this first text box, whats wrong with my input5.onkeydown line? 并且在第一个文本框中都可以正常工作,我的input5.onkeydown行有什么问题吗?

The code you're showing is for highly deprecated JS trigger handling. 您显示的代码用于高度不推荐使用的JS触发器处理。 It's how we did event handling back in the HTML4.01 (1998) era, but it's not how you do event handling in modern HTML and JS. 这就是我们在HTML4.01(1998)时代进行事件处理的方式,但并不是现代HTML和JS中的事件处理方式。

The modern approach is to use event listening, using the addEventListener (and removeEventListener ) functions in a bit of page script (loaded just before </body> so that any elements that need to be found via document.getElementById or document.querySelector can be found): 现代的方法是使用事件侦听,在一些页面脚本(在</body>之前加载)中使用addEventListener (和removeEventListener )函数,以便可以通过document.getElementById或document.querySelector找到需要的任何元素。找到):

var userInput = document.getElementById("userinput");

function dataHandler(evt) {
  var quantity = userInput.value;
  if (validateQuantity(quantity)) {
    // do things
  }
}

userInput.addEventListener("blur", dataHandler);
userInput.addEventListener("keydown", dataHandler);

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

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