未捕获触发的按键事件?

Triggered keypress events not being captured?

我正在从条形码扫描仪(类似于键盘输入)捕获输入,效果很好,但我目前无法使用条形码扫描仪,需要测试我的代码,所以我需要模拟条码扫描器(键盘)输入。

我认为为每个角色触发 keypress 事件会起作用,但它不起作用。这是我的测试代码:

var barcodeScannerTimer;
var barcodeString = '';

// capture barcode scanner input
$('body').on('keypress', function (e) {
    barcodeString = barcodeString + String.fromCharCode(e.charCode);

    clearTimeout(barcodeScannerTimer);
    barcodeScannerTimer = setTimeout(function () {
        processBarcode();
    }, 300);
});

function processBarcode() {
    console.log('inside processBarcode with barcodeString "' + barcodeString + '"');

    if (!isNaN(barcodeString) && barcodeString != '') {  // @todo this check is lame. improve.
        alert('ready to process barcode: ' + barcodeString);
    } else {
        alert('barcode is invalid: ' + barcodeString);
    }

    barcodeString = ''; // reset
}


window.simulateBarcodeScan = function() {
    // simulate a barcode being scanned
    var barcode = '9781623411435';
    for (var i = 0; i < barcode.length; i++) {
        var e   = jQuery.Event("keypress");
        e.which = barcode[i].charCodeAt(0);
        $("body").focus().trigger(e);
    }
}

JSFIDDLE

如果您快速输入数字(如 1234),您会看到输入被正确捕获。但是,点击运行我的测试代码按钮,并没有捕获到输入。触发事件是因为弹出了一个提示框,但是barcodeString是空的!

为什么这不起作用?我应该触发 keypress 以外的其他事件吗?

处理程序正在读取 charCode 但您仅在事件上设置 which。设置 charCode,或从 which 读取。 https://jsfiddle.net/mendesjuan/bzfeuezv/1/

barcodeString = barcodeString + String.fromCharCode(e.which);

触发合成事件

这提醒您,触发合成事件是一项棘手的工作,通常需要您对处理程序有深入的了解(这很糟糕),这样您就不必构建完整的事件对象。另外,请注意并非所有由 jQuery 触发的事件都会实际触发本机事件并导致应用其默认操作。

简单地说,触发 keypress 并不会实际在文本字段中键入字符或触发未使用 jQuery 设置的事件处理程序。

document.querySelector('input').addEventListener('keypress', function() {
  console.log('standard input key press handler');
});


var e = jQuery.Event("keypress");
e.which = "a".charCodeAt(0);
$('input').keypress(function(){
  console.log('jQuery input key press handler');
}).trigger('keypress', e);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="yo" />