keydown事件的新价值

时间:2012-06-06 08:54:08

标签: javascript javascript-events keydown

浏览器:Google Chrome V19.0.1084.52

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

在控制台中,当我在console.log中显示<​​strong>事件时,它将显示 event.srcElement.value ,因为该值将显示,即从12 =&gt; 123,当我在console.log中只显示 event.srcElement.value 时,它将显示为输入,不会显示。

Console.log正在一个接一个地发生,两者之间没有任何停顿。

如何在keydown上找到文本框的新值以及为什么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);
});

CONSOLE.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

6 个答案:

答案 0 :(得分:24)

我不确定它是否可以提供任何帮助,但是当我不得不在事件监听器中处理类似情况时,我使用setTimeout()并且1ms超时,我将主要功能检查为价值等。

这是因为当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();
  }
});

答案 1 :(得分:10)

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

请参阅keypress, keydown, keyup value of input box AFTER eventhttp://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事件。

答案 2 :(得分:0)

我唯一可以想到的是,即使在keydown事件之后,控制台中输出的srcElement对象仍然链接到事件Object,以便控制台中的Object从12更新为123,即使已经在控制台中了。

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

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

答案 3 :(得分:0)

在此处添加@Bergi的评论,以便包括文本选择和插入标记的位置,您可以按以下步骤进行操作:

class Form extends React.Component {
  constructor() {
    super();
    this.state = {
      filename: '',
      showModal: false,
    };
  }

  render() {
    const { filename, showModal } = this.state;

    const onSaveButtonClick = () => {
      this.setState({ showModal: true });
    }

    const onModalSubmit = () => {
      this.setState({ showModal: false });
    }

    ...

    return (
      ...
      <SaveButton
        ...
        filename={this.props.filename}
        onClick={onSaveButtonClick}
      />
      ...
      {showModal ? (
        <SaveDocument
          ...
          onSubmit={onModalSubmit}
          filename={filename}
        />
       ) && null}
    );
  }
}

答案 4 :(得分:0)

因为这是搜索“如何在输入键下获取新值”时出现的第一个结果,所以我在这里发布了一个有效的答案。

这对于很多情况应该足够了,但我建议检查“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',
  ];

答案 5 :(得分:0)

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