Javascript更改输入值

Javascript change input value

本文关键字:输入 Javascript      更新时间:2023-09-26

在我的网站上,我有一个没有显示的框。当用户键入用户名和密码时,如果它们正确,则必须显示该框。在这里你可以看到HTML代码:

<div id="mainbox" style="display: none;">
    <p class="classm">Test.</p>
</div>    
<input type="text" id="user"/>
<br />
<input type="text" id="password" value="a"/>
<br />
<input type="button" value="Log in" onclick="login();">

这里是javascript函数:

function login() {
    var a = document.getElementById('password').value;
    var b = document.getElementById('user').value;
    if ((a == 'qwe') && (b == 'rty')) { //the problem is not here
     document.getElementById('password').style.display="none";
    }
    else
    {
     alert('You are not logged in.');  
    }
}

当我单击按钮Log in时,看起来函数login();没有被调用,因为发生了任何事情。你知道为什么吗?

if (a == 'qwe') && (b == 'rty') //Wrong

封装类似if( condition )的条件

 if ((a == 'qwe') && (b == 'rty') ) //Corect

正如@Frédéric Hamidi所建议的,不需要内括号。

像这样简单的

if (a == 'qwe' && b == 'rty' )

演示此处

如果使用正确

if (a == 'qwe' && b == 'rty' )

小提琴