Javascript - 为什么变量总是空的?
Javascript - why the variable is always empty?
newcode();
由外部输入(键盘或 SNAPI)执行。结果控制台日志显示 barcode_id
有一个值 1234
.
但是当 button_scan()
为 clicked/executed 时,它总是告诉 barcode_id
为空。
如何确保在执行 newcode()
时它真的编辑了 barcode_id
?
var barcode_id = '';
function button_scan() {
if(barcode_id!='') { // WHY????? always empty console shows: 1234
alert("DENY");
return false;
}
// ALLOW
}
function newcode() {
setTimeout(function() {
var new_barcode = $('#barcode').val();
if(new_barcode!='') {
barcode_id = new_barcode;
$('#barcode').val('');
console.log('>>> ', barcode_id); // prints value: 1234
}
}, 500);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value='' name='barcode' id='barcode' onkeydown="newcode();"/>
<button onclick="button_scan()">Button</button>
if(barcode_id!='') //<---If the barcode_id is not an empty string
尝试:
if(barcode_id=='')//<---If the barcode_id IS an empty string
newcode();
由外部输入(键盘或 SNAPI)执行。结果控制台日志显示 barcode_id
有一个值 1234
.
但是当 button_scan()
为 clicked/executed 时,它总是告诉 barcode_id
为空。
如何确保在执行 newcode()
时它真的编辑了 barcode_id
?
var barcode_id = '';
function button_scan() {
if(barcode_id!='') { // WHY????? always empty console shows: 1234
alert("DENY");
return false;
}
// ALLOW
}
function newcode() {
setTimeout(function() {
var new_barcode = $('#barcode').val();
if(new_barcode!='') {
barcode_id = new_barcode;
$('#barcode').val('');
console.log('>>> ', barcode_id); // prints value: 1234
}
}, 500);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value='' name='barcode' id='barcode' onkeydown="newcode();"/>
<button onclick="button_scan()">Button</button>
if(barcode_id!='') //<---If the barcode_id is not an empty string
尝试:
if(barcode_id=='')//<---If the barcode_id IS an empty string