javascript keydown 事件新值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10911047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:27:32  来源:igfitidea点击:

keydown event new value

javascriptdom-eventskeydown

提问by William Isted

Browser: Google Chrome V19.0.1084.52

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

I have a textbox which needs to be a number less than or equal to 255, on keydown I want to check if this value is above or equal to 255 else prevent the event.

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

In the Console when I console.log the eventit will show event.srcElement.valueas the value will appear i.e. from 12 => 123, when I console.log just event.srcElement.valueit will show as the input was, not will be.

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

Console.log's are happening one after the other, nothing in between, no pauses.

Console.log 一个接一个地发生,中间没有任何内容,没有停顿。

How can I find what the new value of a textbox will be on keydown and why is the console.log returning different results?

如何在 keydown 上找到文本框的新值,以及为什么 console.log 返回不同的结果?

Here's my code:

这是我的代码:

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);
});

Console.log:

控制台日志:

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

event.srcElement:

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

回答by Kane Cohen

I'm not sure if it could be of any help, but when I had to deal with a similar situation in an event listener I used a setTimeout()with 1ms timeout where I put the main functionality checking for the value, etc.

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

That is because when the keydownevent is fired the input field is not yet populated with the new data.

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

Simple jQuery example:

简单的 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);
});

UPDATE

更新

Use 'input' event in modern browsers.

在现代浏览器中使用 '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();
  }
});

回答by Bergi

You should not use keydownbut keypress. Then you will receive the actual character code of the char to-be-typed.

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

See keypress, keydown, keyup value of input box AFTER event, http://www.quirksmode.org/dom/events/keys.htmland especially http://www.quirksmode.org/js/keys.html.

请参阅事件后输入框的 keypress、keydown、keyup 值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);

If you just want to get the input value after something is typed, you need to use the keyupevent.

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

回答by Martin

Adding on @Bergi's comment here, so as to include text selections and caret position, you can do it as follows:

在此处添加@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);

回答by Willem Mulder

The only thing I can come up with is that the srcElement Object that is outputted in the console is still linked to the event Object, even after the keydown Event so that the Object in the console is updated from 12 to 123 even when already in the console.

我唯一能想到的是,控制台中输出的 srcElement 对象仍然链接到事件对象,即使在 keydown 事件之后,控制台中的对象也会从 12 更新为 123,即使已经在安慰。

It doesn't happen with the direct output of event.srcElement.value because that is a literal value and is copied on logging, not referenced...

它不会发生在 event.srcElement.value 的直接输出中,因为它是一个文字值并且在日志记录时被复制,而不是被引用......

If you would be real fast you could check if you could see it change in the Console from 12 to 123 ;-)

如果您真的很快,您可以检查是否可以在控制台中看到它从 12 更改为 123 ;-)