首先,開宗明義:掃碼槍就是一個輸入工具,類似鍵盤,不過輸入速度快,而且可以設置輸入完成后自動觸發回車。
參考文檔:
-
了解鍵盤的3個事件:onkeydown、onkeypress、onkeyup
-
鏈接的示例程序中有一個String.fromCharCode方法,這個方法將 Unicode 編碼轉為一個字符,因為鍵盤事件的代碼是Unicode編碼
-
keyCode,charCode,which的區別,參考博客1,參考博客2,根據瀏覽器不同,鍵盤觸發的事件不同,選取合適的代碼,(煩人的兼容性~)
-
“掃碼槍本質是觸發鍵盤事件。掃描過程就像是在鍵盤上敲擊相應的鍵,keycode和鍵盤是一一對應的,只是輸入速度(間隔時間)比物理鍵盤輸入要快得多”,實例參考1,實例參考2,
參考上述,即可實現掃碼槍功能,我用到的比較簡單,實際代碼附下:
$(function () { //監聽input回車事件,textbox('textbox')是因為我是用了EasyUI,需要加上這個以獲取Jquery對象,原生input可刪掉 $("#inputId").textbox('textbox').on("keyup", function (e) { if (e.keyCode == '13') { //搜索函數 } }); //方便人員操作,點擊輸入框即清空之前的數據 $("#inputId").textbox('textbox').on("click", function (e) { $('#inputId').textbox('clear'); }); //初始化時聚焦,方便人員操作,進頁面后不用手動點選輸入框 $('#inputId').textbox('textbox').focus(); })
補充知識:
1. JQuery的on綁定事件,on可以用來綁定多個事件,綁定自定義事件(trigger),傳遞參數,向未來元素添加動作等。$(selector).on(event,childSelector,data,function)
注意區分代碼1和代碼2的區別,代碼2之后添加的<p>無動作~

<!DOCTYPE html> <html> <head> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("div").on("click","p",function(){ $(this).slideToggle(); }); $("button").click(function(){ $("<p>This is a new paragraph.</p>").insertAfter("button"); }); }); </script> </head> <body> <div style="background-color:yellow"> <p>This is a paragraph.</p> <p>Click any p element to make it disappear. Including this one.</p> <button>Insert a new p element after this button</button> </div> </body> </html>

<!DOCTYPE html> <html> <head> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("p").on("click",function() { $(this).slideToggle(); }); $("button").click(function(){ $("<p>This is a new paragraph.</p>").insertAfter("button"); }); }); </script> </head> <body> <div style="background-color:yellow"> <p>This is a paragraph.</p> <p>Click any p element to make it disappear. Including this one.</p> <button>Insert a new p element after this button</button> </div> </body> </html>
2. JQuery的trigger方法觸發事件,$(selector).trigger(event,eventObj,param1,param2,...)