在jQuery中推进阶段

时间:2013-06-08 17:07:21

标签: javascript jquery

我有以下代码,我对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 + '.');
        }
    });

1 个答案:

答案 0 :(得分:1)

你所拥有的东西没有多大意义,所以我猜这就是你要做的事情:

$(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 = "";
        }
    });
});

FIDDLE

stage在设置为零之后没有办法可以是零以外的任何东西吗? 事件处理程序内部发生的事情发生在“稍后”,所以在事件处理程序之后检查stage仍然给你......等待它......零?