![](/img/trans.png)
[英]Events triggered by dynamically generated element are not captured by event handler
[英]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);
}
}
如果您快速輸入數字(如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" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.