我有以下代码,我对JavaScript比较陌生,所以谁能告诉我为什么它没有推进到第1阶段+告诉我它是如何完成的?
var textContainer = '#text';
var inputLine = 'input';
var username = null;
var stage = 0;
$(function(){
if(0 == stage){
$(function(){
$(textContainer).text('What is your name?');
$(inputLine).focus();
$(inputLine).keypress(function(e){
if (e.keyCode == 13 && !e.shiftKey) {
e.preventDefault();
username = $(this).val();
$(this).val('');
stage = 1;
}
});
});
}
if(1 == stage){
$(textContainer).text('Hi there, ' + username + '.');
}
});
你在那里的东西没有多大意义,所以我猜这就是你想做的:
$(function(){
var textContainer = $('#text'),
inputLine = $('input');
textContainer.text('What is your name?');
inputLine.focus().on('keyup', function(e){
if (e.which === 13) {
e.preventDefault();
textContainer.text('Hi there, ' + this.value + '.');
this.value = "";
}
});
});
小提琴
在stage
被设为0之后,它就不可能是0以外的任何东西了吗?
事件处理程序内部发生的事情"稍后"发生,因此在事件处理程序之后检查stage
仍然会给您…等一下....零?