输入值未定义?

Input value undefined?

enter image description here我试图创建一个基于输入值(用户和传递)添加用户的函数,但我得到 undefined

let button = document.getElementById("register");

var dataBase = [];

button.addEventListener("click", function (){
      let user = document.getElementsByClassName("username").value;
      let pass = document.getElementsByClassName("password").value;
      dataBase.push({user,pass});
      console.log(dataBase)
})
<input class="username" type="text" placeholder="Enter username"/>
<input class="password" type="text" placeholder="Enter password"/>

输入值未定义?因为 getElementsByClassName() return array 元素到元素所以得到第一个元素 document.getElementsByClassName("password")[0].value

let button = document.getElementById("register");

var dataBase = [];

button.addEventListener("click", function (){
      let user = document.getElementsByClassName("username")[0].value;
      let pass = document.getElementsByClassName("password")[0].value;
      dataBase.push({user,pass});
      console.log(dataBase)
})
<input class="username" type="text" placeholder="Enter username"/>
<input class="password" type="text" placeholder="Enter password"/>

<button id="register" >register</button>

使用下面的代码

let button = document.getElementById("register");

var dataBase = [];

document.getElementById("submit").addEventListener("click", function (){

      let user = document.getElementById("username").value;
      let pass = document.getElementById("password").value;
      
      dataBase.push({user,pass});
      console.log(dataBase)
})
<input class="username" id="username" type="text" placeholder="Enter username"/>
<input class="password" id="password" type="text" placeholder="Enter password"/>
<button id="submit">Submit</button>

首先你必须知道 getElementsByClassName() return 是 HTMLCollection。这就是为什么 .value return undefined.

通过将 id 应用于元素并通过 getElementById() 获取数据的最佳实践。

因此您的代码将是:

button.addEventListener("click", function (){
      let user = document.getElementById("myUser").value;
      let pass = document.getElementById("myPass").value;
      dataBase.push({user,pass});
      console.log(dataBase)
})

而html是:

<input class="username" id="myUser" type="text" placeholder="Enter username"/>
<input class="password" id="myPass" type="text" placeholder="Enter password"/>

但如果您仍想使用 getElementsByClassName() 获取值,那么这里是解决方案:

let user = document.getElementsByClassName("username")[0].value;
let pass = document.getElementsByClassName("password")[0].value;

因为他们 return collection 并假设在 HTML DOM.[=17= 中没有可用的相同 class 的元素]