简体   繁体   English

变量未定义 javascript

[英]Variable is undefined javascript

Hello I made a "login screen" that when you enter a name you will be transfer to another html file.您好,我制作了一个“登录屏幕”,当您输入名称时,您将被转移到另一个 html 文件。 I made a welcome back screen that says Welcome back, "username".我做了一个欢迎回来的屏幕,上面写着欢迎回来,“用户名”。 But for some reason the variable that I use to take the value of the username field is undefined.但是由于某种原因,我用来获取用户名字段值的变量是未定义的。 This is the login screen html code:这是登录屏幕的 html 代码:

<form id="login-form" metod="post" action="main.html">
      <div class="txt_field">
          <input id="username" type="text" required>

          <label>username</label>
      </div>
      <input onclick="validate()" type="submit" id="submit" value="Login">
  </form>
</div>
<script type="text/javascript" src="functions.js"></script>

-> this is the js file: -> 这是 js 文件:

let username1;
function validate(){
   username1=document.getElementById(username).value;
}
document.getElementById('show_username').innerHTML = username1;

-this is the after login html file - 这是登录后的 html 文件

<center>
    <h1>Welcome back,<br>
      <span id="show_username"></span>
  </h1>
  </center>
  <script type="text/javascript" src="functions.js"></script>

**ofc I didn't include all the code for basic reasons. **ofc 出于基本原因,我没有包含所有代码。

Here is what happens in JavaScript when you load your page:以下是加载页面时 JavaScript 中发生的情况:

// username1  is set to null
let username1;
// validate() function is created
function validate(){
   username1=document.getElementById(username).value;
}
// show_username element is populated with username1 (still null)
document.getElementById('show_username').innerHTML = username1;

When you call the validate function, username1 is updated but document.getElementById('show_username') is not.当您调用验证函数时, username1会更新,但document.getElementById('show_username')不会。

You also are referencing a username variable instead of 'username' as a string.您还将username变量而不是'username'作为字符串引用。

Your code will work if you move line 5 into the validate function, and fix that issue.如果您将第 5 行移动到validate函数中并修复该问题,您的代码将起作用。

let username1;
function validate(){
   username1=document.getElementById('username').value;
   document.getElementById('show_username').innerHTML = username1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM