javascript 有没有DOM元素来做这个或者类似的东西?

r1zhe5dt  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(97)

我是一个初学者,我有一些问题,我的HTML和JavaScript代码。主要是我想发送一个通知,如“登录!”和“填写剩余的数据”。
下面是HTML代码:

<input type="email" id="emailToLogin" placeholder="Enter your email" />
<input type="password" id="passwordToLogin" placeholder="Enter your password"/>

 <button type="submit" id="log" onclick="notification(emailInput, passwordInput)">
 <p>
    Log in
 </p>
</button>
<h1 id="successful"></h1>
<h1 id="unsuccessful"></h1>

字符串
JavaScript代码:

let emailInput = document.getElementById("emailToLogin");
let passwordInput = document.getElementById("passwordToLogin");

function notification(emailInput, passwordInput) {
    if (emailInput ==  "" || passwordInput == "") {
        document.getElementById("unsuccessful").innerHTML = "Please enter the remaining data!";
    }

}


更具体地说,我想用JavaScript来做这件事,无论如何。我有一个代码用于重定向到这个小项目的主站点,但我认为这并不重要。
我已经尝试将“”更改为undefined或null,但不起作用。

xytpbqjk

xytpbqjk1#

这不是你想的那样

if (emailInput ==  "" || passwordInput == "") {

字符串
如果你使用console.log(emailInput)(和/或passwordInput),你会看到这些不是字符串值,它们是整个DOM元素。你在这里从DOM查询:

let emailInput = document.getElementById("emailToLogin");
let passwordInput = document.getElementById("passwordToLogin");


为了比较它们的 * 值 *,你需要从元素中读取值:

if (emailInput.value ==  "" || passwordInput.value == "") {


此外,我怀疑你很容易被多个同名变量搞糊涂。你全局定义了这些变量:

let emailInput = document.getElementById("emailToLogin");
let passwordInput = document.getElementById("passwordToLogin");


然后在这里用局部变量隐藏它们:

function notification(emailInput, passwordInput) {


这很巧合地起作用,因为你碰巧将这些全局变量传递给函数:

onclick="notification(emailInput, passwordInput)"


但这是一个等待发生的错误。保持意图清晰。您可以为局部变量使用不同的名称,并期望值而不是整个元素:

function notification(email, password) {
  if (email ==  "" || password == "") {
    document.getElementById("unsuccessful").innerHTML = "Please enter the remaining data!";
  }
}


然后传递这些值:

onclick="notification(emailInput.value, passwordInput.value)"


或者仅仅依赖于全局变量而不使用函数参数:

function notification() {
  if (emailInput.value ==  "" || passwordInput.value == "") {
    document.getElementById("unsuccessful").innerHTML = "Please enter the remaining data!";
  }
}


当然,从函数调用中删除参数:

onclick="notification()"


这真的取决于你喜欢哪种方法。

相关问题