键按下事件新值

keydown event new value

本文关键字:新值 事件      更新时间:2023-09-26

浏览器: 谷歌浏览器 V19.0.1084.52

我有一个文本框,它需要是一个小于或等于 255 的数字,在按键时我想检查这个值是否大于或等于 255,否则会阻止该事件。

当我控制台时.log事件将显示 event.srcElement.value,因为值将出现,即从 12 => 123,当我控制台时.log只是 event.srcElement.value 它将显示为输入,而不是。

控制台.log一个接一个地发生,中间没有任何东西,没有停顿。

如何找到文本框在按键时的新值,为什么控制台.log返回不同的结果?

这是我的代码:

function inputNumeric(event,max) {
    console.log (event);
    console.log ('event.originalEvent.srcElement.value: '+event.originalEvent.srcElement.value);
    console.log ('event.srcElement.value: '+event.srcElement.value);
}
$("#rs485addr").keydown(function(event) {
    inputNumeric(event);
});

控制台.log:

event.originalEvent.srcElement.value: 12
event.srcElement.value: 12

event.srcElement:

accept: ""
accessKey: ""
align: ""
alt: ""
attributes: NamedNodeMap
autocomplete: ""
autofocus: false
baseURI: "http://10.50.50.60/controller/?bid=10"
checked: false
childElementCount: 0
childNodes: NodeList[0]
children: HTMLCollection[0]
classList: DOMTokenList
className: "width-60"
clientHeight: 18
clientLeft: 2
clientTop: 2
clientWidth: 62
contentEditable: "inherit"
dataset: DOMStringMap
defaultChecked: false
defaultValue: "1"
dir: ""
dirName: ""
disabled: false
draggable: false
files: null
firstChild: null
firstElementChild: null
form: null
formAction: ""
formEnctype: "application/x-www-form-urlencoded"
formMethod: "get"
formNoValidate: false
formTarget: ""
hidden: false
id: "rs485addr"
incremental: false
indeterminate: false
innerHTML: ""
innerText: ""
isContentEditable: false
jQuery17102950612970162183: 22
labels: NodeList[1]
lang: ""
lastChild: null
lastElementChild: null
localName: "input"
max: ""
maxLength: 3
min: ""
multiple: false
name: ""
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: null
nextSibling: Text
nodeName: "INPUT"
nodeType: 1
nodeValue: null
offsetHeight: 22
offsetLeft: 183
offsetParent: HTMLBodyElement
offsetTop: 365
offsetWidth: 66
onabort: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
onchange: null
onclick: null
oncontextmenu: null
oncopy: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onmousedown: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onreset: null
onscroll: null
onsearch: null
onselect: null
onselectstart: null
onsubmit: null
onwebkitfullscreenchange: null
onwebkitfullscreenerror: null
onwebkitspeechchange: null
outerHTML: "<input class="width-60" id="rs485addr" maxlength="3" type="textbox" value="1">"
outerText: ""
ownerDocument: HTMLDocument
parentElement: HTMLSpanElement
parentNode: HTMLSpanElement
pattern: ""
placeholder: ""
prefix: null
previousElementSibling: HTMLLabelElement
previousSibling: Text
readOnly: false
required: false
scrollHeight: 16
scrollLeft: 0
scrollTop: 0
scrollWidth: 60
selectionDirection: "forward"
selectionEnd: 3
selectionStart: 3
size: 20
spellcheck: true
src: ""
step: ""
style: CSSStyleDeclaration
tabIndex: 0
tagName: "INPUT"
textContent: ""
title: ""
translate: true
type: "text"
useMap: ""
validationMessage: ""
validity: ValidityState
value: "123"
valueAsDate: null
valueAsNumber: NaN
webkitGrammar: false
webkitRegionOverflow: "undefined"
webkitSpeech: false
webkitdirectory: false
webkitdropzone: ""
willValidate: true

我不确定它是否有任何帮助,但是当我不得不在事件侦听器中处理类似情况时,我使用了超时为 1 毫秒的setTimeout(),我在其中放置了主要功能检查值等。

这是因为触发keydown事件时,输入字段尚未填充新数据。

简单的jQuery示例:

$('#input').on('keydown', function(e) {
  var field = $(this);
  var prevValue = field.val();
  setTimeout(function() {
    // check if new value is more or equal to 255
    if (field.val() >= 255) {
      // fill with previous value
      field.val(prevValue);
    }
  }, 1);
});

更新

在现代浏览器中使用"input"事件。

var prevValue = 0;
$('#input').on('input', function(e) {
  var field = $(this);
  // check if new value is more or equal to 255
  if (field.val() >= 255) {
    // fill with previous value
    field.val(prevValue);
  } else {
    // If value is lower than 255 set it in prev value.
    prevValue = field.val();
  }
});

你不应该使用keydown,而应该使用keypress。然后,您将收到要键入的字符的实际字符代码。

请参阅按键、按键、输入框 AFTER 事件的键控值、http://www.quirksmode.org/dom/events/keys.html,尤其是 http://www.quirksmode.org/js/keys.html。

inputElement.addEventListener("keypress", function(e) {
     var curval = e.srcElement.value;
     var newchar = String.fromCharCode(e.charCode || e.keyCode);
     if (/* condition */)
         e.preventDefault();
}, false);

如果只想在键入某些内容后获取输入值,则需要使用 keyup 事件。

由于这是搜索"如何在输入键下获取新值"时出现的第一个结果,因此我在此处发布一个有效的答案。

对于很多情况来说,这应该足够了,但我建议检查"keyup"或"input"或任何其他事件是否更适合您的个人问题。

function getNewInputValue(e) {
      let newValue = e.target.value;
      let valueArray = newValue.split('');
      const selectionLength = (e.target.selectionEnd - e.target.selectionStart);
      if (e.key === 'Backspace') {
        if (selectionLength === 0 && e.target.selectionStart > 0) {
          valueArray.splice(e.target.selectionStart - 1, selectionLength + 1);
        } else {
          valueArray.splice(e.target.selectionStart, selectionLength);
        }
      } else if (e.key === 'Delete') {
        if (selectionLength === 0) {
          valueArray.splice(e.target.selectionStart, selectionLength + 1);
        } else {
          valueArray.splice(e.target.selectionStart, selectionLength);
        }
      } else {
        valueArray.splice(e.target.selectionStart, selectionLength, e.key);
      }
      newValue = valueArray.join('');
      return newValue;
}

如果您使用此截图来防止输入,如果新值不符合您的标准,您还应考虑不检查按下键何时触发某些"生活质量"功能。

我说的是使用箭头键在输入内导航,或通过按 tab 键等导航到下一个控件。

这些是我忽略的键:

const ignoredKeys = [
    'ArrowLeft',
    'ArrowRight',
    'Tab',
    'End',
    'Home',
    'ArrowUp',
    'ArrowDown',
  ];

我唯一能想到的是,即使在键关闭事件之后,控制台中输出的 srcElement 对象仍然链接到事件对象,因此控制台中的对象即使已经在控制台中也从 12 更新到 123。

事件.srcElement.value 的直接输出不会发生这种情况,因为这是一个文字值,在日志记录中复制,而不是引用......

如果你真的很快,你可以检查你是否能在控制台中看到它从 12 到 123 的变化;-)

在此处添加@Bergi的评论,以便包括文本选择和插入符号位置,您可以执行以下操作:

inputElement.addEventListener("keypress", (event) => {
    let curval = event.srcElement.value;
    let newchar = String.fromCharCode(event.charCode || event.keyCode);
    let curval_arr = curval.split("");
    curval_arr.splice(event.target.selectionStart, (event.target.selectionEnd - event.target.selectionStart), newchar);
    let newval = curval_arr.join("");
    //TODO: your logic here with "newval" containing the value to be.
    //console.log(curval, newchar, newval);
    //event.preventDefault();
}, false);

简单的解决方案:只需使用 keyup 事件(而不是 keydown 事件)。这将在用户键入最新字符为您提供最新值。这样就解决了问题。