javascript - 按键事件新值

标签 javascript dom-events keydown

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

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

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

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

我如何找到文本框的新值将在按键时是什么以及为什么 console.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);
});

控制台日志:

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

事件源元素:

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

更新

在现代浏览器中使用“输入”事件。

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

关于javascript - 按键事件新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10911047/

相关文章:

javascript - 使用 Require.js 在页面上运行 Q

javascript - 在history.pushState之后导航回来时恢复原始页面

javascript - 如何从 20 个按钮的列表中查找单击了哪个按钮?

Python Kivy - 如何对多次按键使用react?

objective-c - 在 keyDown 事件中获取 modifierFlags 而无需同时按下非修饰键!

javascript - 在 CKEditor 中删除 HTML 元素

javascript - IE10 计算宽度的问题

javascript - 拦截 Chrome 浏览器中的 PageUp/PageDown 按键事件

javascript - 加载大小的图像事件

phantomjs - 如何在casperjs/phantomjs中模拟 "press and hold"(长按)按键 Action ?