对于这个问题,我制作了一个功能性的 JSfiddle:http://jsfiddle.net/KSCLC/
我正在制作一个简单的页面,您可以在其中扫描或键入 UPC,它会自动添加到表格中以供显示。我废弃了一些代码以启动一个计时器,该计时器在输入完成后等待 3 秒,然后在我的表中创建一个新行以显示输入的 UPC 和项目信息。
虽然这段代码有一些问题。 (我的问题)
A.) 当您手动输入 UPC 时,新行操作会发生多次(为同一个 upc 插入多行)但是当您使用条形码扫描器扫描 UPC 时,它只会完成一次操作。 (这是正确的)
B.) 当您从字段中删除信息(将 upc 字段设为空白)时,新行操作会再次发生,但会插入一个空白行。
C.) 我试图在插入行后将 upc 字段设为空白,但那没有发生。我尝试在行插入之后放置 upc='';
但这没有用。我将 upc
定义为:
var upc=document.getElementById("UPC").value;
(正如您在下面和 jsFiddle 中看到的那样。)
那么现在的代码......
我只是为 upc 字段使用了一个简单的输入:
<input type="text" id="UPC" name="UPC" class="form-control scanning" autofocus="autofocus" placeholder="Scan or enter UPC here" />
和扫描项目的简单表格
<div class="scannedItems">
<table class="table table-hover" id="ScannedItems">
<thead>
<tr>
<th>UPC</th>
<th>Description</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>8754621160</td>
<td>Example Product</td>
<td>$5.00</td>
<td>5lbs</td>
<td>$25.00</td>
<td>
<a><span class="glyphicon glyphicon-plus" style="padding-right:15px"></span></a>
<a><span class="glyphicon glyphicon-minus"></span></a>
</td>
</tr>
</tbody>
</table>
</div>
然后是我的 Javascript
//setup before functions
var field = document.getElementById("UPC");
var typingTimer; //timer identifier
var doneTypingInterval = 3000; //time in ms, 3 seconds
//on keyup, start the countdown
$('#UPC').keyup(function () {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#UPC').keydown(function () {
clearTimeout(typingTimer);
});
//user is "finished typing," do something
if (field.value.length == 0) {
//do nothing
} else {
function doneTyping() {
var upc = document.getElementById("UPC").value;
var table = document.getElementById("ScannedItems");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = upc;
cell2.innerHTML = "Example Description";
cell3.innerHTML = "$3.00";
cell4.innerHTML = "7lbs";
cell5.innerHTML = "$21.00";
cell6.innerHTML = "<a><span class='glyphicon glyphicon-plus' style='padding-right:15px;'></span></a><span> </span><a><span class='glyphicon glyphicon-minus'></span></a>";
upc = '';
}
}
最佳答案
工作:http://jsfiddle.net/QAbGS/1/
1) 你应该总是在重置之前清除旧计时器,只是覆盖变量并不能清除它。 keydown 事件可能无法及时到达那里以从之前清除它,因此在 keyup 中清除它可以解决此问题。
$('#UPC').keyup(function(){
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
2) 你在函数外进行 npc 长度检查,这应该在函数内!
function doneTyping () {
if (field.value.length != 0) {
3) 您将文本框的值保存到名为 npc 的变量中。然后您将此变量设置为空,而不是文本框!你应该做 textbox.value = '' 来重置它。
field.value = '';
关于Javascript "Stop Typing"计时器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19080241/