簡體   English   中英

如何將按鍵事件偵聽器添加到我在 javascript 中動態創建的輸入文本字段中?

[英]How to add a keypress event listener into my dynamically created input text field in javascript?

我想在我的輸入文本字段中添加一個keypress監聽器。 這是我的代碼:

var input = document.createElement("input");
input.type = "text";
input.id="vac";
input.addEventListener("keypress",(e) => {return IsAlphaNumeric(e);});

function IsAlphaNumeric(e) { //prohibits input of all special characters except for `/`
  var specialKeys = new Array();
  specialKeys.push(8);  //Backspace
  specialKeys.push(9);  //Tab
  specialKeys.push(46); //Delete
  specialKeys.push(36); //Home
  specialKeys.push(35); //End
  specialKeys.push(37); //Left
  specialKeys.push(39); //Right
  var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
  var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));

  if(e.charCode==47){
      ret=true;
  }
  return ret;
}

現在,當我執行代碼時, keypress監聽器不起作用。 怎么了? 我該如何解決?

如果你想防止非字母數字字符,除了/ ,這是現代的方法。 使用event.preventDefault() 一個簡單的 RegExp 就足以進行字符串測試。

 const input = document.createElement('input'); input.type = 'text'; input.id = 'vac'; const shouldPrevent = (str) => !/[a-zA-Z\À-\ÿ\\d\\/]/.test(str); input.addEventListener('keydown', (e) => { if (shouldPrevent(e.key) && e.cancelable) { e.preventDefault(); } }); document.getElementById('root').appendChild(input);
 <div id="root"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM