Javascript突然无法读取值

0 html javascript jquery getelementbyid

我正在编写一个客户端应用程序,鉴于这些成分将为您提供鸡尾酒配方.输入后,单击按钮将搜索成分.如果输入"all",您将被重定向到包含所有配方的页面.

我刚刚开始这么说,所有功能都是我做过的唯一部分.它工作正常.为了练习,当你输入"all"时它会重定向到facebook的url.无处不在(没有新的变化)它开始给我一个错误,它没有读取输入,它正在读取它为null.

相关的HTML:

<input type="text" id="alcohol">
<h4 class="btn" type="submit" onclick="whole()"> Search</h4>
Run Code Online (Sandbox Code Playgroud)

JS:

var input = document.getElementById('alcohol').value;

function whole() {
    if (input == "all") {
        window.location = "http://www.facebook.com";
    };
};
Run Code Online (Sandbox Code Playgroud)

这里发生了什么事?它为什么停止工作?

jfr*_*d00 7

我们需要确定一个更大的背景知识,但看起来你可能在包含最新价值之前很快得到了酒精值.

您可以更改为此选项以使该whole()功能与酒精字段的当前值一起使用:

  function whole(){
    var input = document.getElementById('alcohol').value;
    if (input =="all"){
      window.location="http://www.facebook.com";
    };
  };
Run Code Online (Sandbox Code Playgroud)

记住这个:

var input = document.getElementById('alcohol').value;
Run Code Online (Sandbox Code Playgroud)

获取代码行运行时的当前值.对该字段的任何未来更改都不会影响该input变量.该变量仅包含特定时间点的值.避免这类问题的最简单方法是在需要时获得正确的价值,而不是早些时候.