简体   繁体   English

输入的jQuery触发键盘获取旧值

[英]jQuery trigger keyup on input gets old value

I try to manually trigger key-up event in qunit test but it fails since manually trigger key-up event will not change the input value. 我尝试在qunit测试中手动触发键盘输入事件,但由于手动触发键盘输入事件不会更改输入值,因此失败。

http://jsfiddle.net/Re9bj/4/ http://jsfiddle.net/Re9bj/4/

$('input').on('keyup', function (event) {
    $('div').html($('input').val());
});

var e = $.Event('keyup', {
    keycode: 68
});
$('input').trigger(e); //this trigger will not change the input value

This trigger will work but the problem is that input value never change. 该触发器将起作用,但问题是输入值永远不会改变。

You can't add a character with a simple trigger. 您不能使用简单的触发器添加字符。 Trigger will only fire events, but not the default behavior. 触发器将仅触发事件,而不触发默认行为。 You need to simulate it. 您需要模拟它。

To do that, you can use this code : 为此,您可以使用以下代码:

if(event.isTrigger && event.keycode) this.value +=  String.fromCharCode(event.keycode);

It will check if the event is triggered and then print the value. 它将检查事件是否被触发,然后打印该值。

Final code : 最终代码:

$('input').on('keyup', function (event) {
    if(event.isTrigger && event.keycode) this.value +=  String.fromCharCode(event.keycode);
    $('div').html($('input').val());
});

var e = $.Event('keyup', {
    keycode: 68
});
$('input').trigger(e);

Fiddle : http://jsfiddle.net/Re9bj/9/ 小提琴: http : //jsfiddle.net/Re9bj/9/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM