0

我正在尝试获取一个人当前在 keyup 上使用的输入框的值和名称,但是一旦 keyup 函数运行,我就无法更新全局变量。他们只是继续在 Google Chrome 开发人员工具中说未定义。

我究竟做错了什么?

$( document ).ready(function() {
                var assessName;
                var assessVal;
                var impName;
                var impVal;

                //Get the name and value of the currently selected assessed input
                $('[id^=ass]').on('keyup', function(){
                    assessName = $(this).attr('name').replace('ass-','');
                    assessVal = $(this).val();
                });

                //Get the name and value of the currently selected implemented input
                $('[id^=imp]').on('keyup', function(){
                    impName = $(this).attr('name').replace('imp-','');
                    impVal = $(this).val();             
                });

                console.log(assessName);
                console.log(assessVal);
                console.log(impName);
                console.log(impVal);
            });
4

1 回答 1

2

发生这种情况是因为keyup事件variables 您将它们写入控制台后发生了变化。JavaScript 中的事件是异步的。

因此,如果您将console.log调用放入事件侦听器中,它将准确显示您的期望。

于 2013-10-30T22:17:39.680 回答